我想测试C int
中是否设置了任何单个位。我不在乎它是哪一位。
等同于
if (1 == count_bits (n))
我很好奇是否有一种不需要特殊硬件支持的非循环算法。
答案 0 :(得分:5)
如果仅设置一位,则该数字为2的幂。
unsigned int IsPowerOfTwoNoLoop(unsigned int input)
{
unsigned int temp = input;
if(0 == input)
{
return 0;
}
temp -= 1;
/*Example of the logic:*/
/* 0100 (4 DEC) - 1 = 0011
0011 & 0100 = 0000
*/
if (temp & input) /* if not zero - not pow of two */
{
printf("%u Is NOT the power of two !\n", input);
return 0;
}
printf("%u Is the power of two !\n", input);
return 1;
}
答案 1 :(得分:1)
最简单的方法可能是转换为无符号类型。
然后,我们只是在测试是否具有2的精确乘方。
我们可以简单地观察到,这是唯一与n-1
没有相同位的非零数字:
bool is_power_of_two(unsigned int n)
{
return n && ! (n & (n-1));
}