判断x是否为2的若干次幂
关键运算 i & (i - 1)
i 和 i-1的二进制区别,i若为2的若干次幂,则i与i-1的区别为相反
----------------
1
0000000000000001
0000000000000000
0000000000000000
1
----------------
2
0000000000000010
0000000000000001
0000000000000000
1
----------------
4
0000000000000100
0000000000000011
0000000000000000
1
----------------
8
0000000000001000
0000000000000111
0000000000000000
1
----------------
16
0000000000010000
0000000000001111
0000000000000000
1
----------------
32
0000000000100000
0000000000011111
0000000000000000
1
----------------
64
0000000001000000
0000000000111111
0000000000000000
1
----------------
128
0000000010000000
0000000001111111
0000000000000000
1
测试代码:
#include <iostream>
#include <bitset>
int main()
{
for (int i = 1; i<=1024; i = 2*i)
{
cout<<"----------------"<<endl;
cout<<i <<endl;
cout<<bitset<16>(i)<<endl;//二进制输出i
cout<<bitset<16>(i-1)<<endl;//二进制输入i-1
cout<<bitset<16>(i & (i - 1))<<endl;
cout<<((i & (i - 1))?0:1)<<endl;//判断是否为2的若干次幂
}
system("pause");
return 0;
}