c++ - 2^power 不使用 math.pow 和乘法

标签 c++

有没有什么方法可以在不使用 math.pow 或乘法运算符的情况下使用代码 2^power。 到目前为止,

虽然我使用了 2 个计数器和加法器,但我的程序似乎无法正常工作。这是我到目前为止的工作。

int counter=0; // k 
int userNumber=0; // p 
int power=0;
int sum=0;

cout << "Enter a non-negative number: ";
cin >> userNumber;


while (userNumber > counter)
{
    power +=2;
    counter++;
    power++;
}

sum = power - 1;
// post-condition: Sum = 2^p -1
cout << "The output is " << sum << endl;
return 0;

最佳答案

您可以使用位操作计算 2^n。简单地做:

1 << n;

这是可行的,因为二进制数左移相当于乘以 2。

关于c++ - 2^power 不使用 math.pow 和乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523773/

相关文章:

c++ - 在 C++ 中创建一堆对象

c++ - 确定升压变体中的最大 sizeof()

c++ - 延迟构造函数调用

c++ - Xcopy文件到pro/pri文件中的新目录

c++ - 在 MFC 中填充下拉列表

c++ - 将成员函数添加到绑定(bind)到 Lua 的 C++ 类

C++ - 顺序多线程输出

c++ - GCC 错误 : explicit specialization in non-namespace scope

c++ - 意外的复制构造函数

c++ - Cout 不会打印我的字符串