//目标:验证64位输入是2的幂。如果数字不是2的幂,找到前一个值,即2的幂。
使用namespace std;
int main() {
//Input. 64 bit number
unsigned long long int input = 13174607262084689114;
//Check number is power of two.
if (!((input && (input & (input - 1))) == 0)) {
cout<<"The number is not Power of 2"<<endl;
//Find the previous value of input, which should be power of 2.
//Step 1 : Find the Next power of 2 for the input.
//Step 2 : divide the number by 2
/*End*/
// Step 1
input |= input >> 1;
input |= input >> 2;
input |= input >> 4;
input |= input >> 8;
input |= input >> 16;
input |= input >> 32;
input = input + 1; // input holds next number , power of 2.
// Step 2
input = input >> 1;
cout<<"Power of 2: 64 bit: "<<input<<endl;
}
return 0;
}
答案 0 :(得分:1)
(!((input) && (input & (input - 1))) == 0)
这应该是
(!(input && (input & (input - 1)) == 0))
答案 1 :(得分:0)
您的代码似乎有些令人困惑。如果你只想获得下一个最接近的或等于2的幂的数字,那么一种方法就是简单地计算二进制中的数字然后再移回1:
//assuming x is a positive number
long long closest_pow2(long long x)
{
int c = -1;
while (x)
{
x >>= 1;
c++;
}
return ((long long)1) << c;
}
如果x可以为零,您可能需要检查零。