1.判断一个数转换成2进制之后1的个数
注:每次进行一次x&(x-1) ,会把x最右边的1变为0
2.判断一个数是否为2的n次方
注:一个数如果是2的n次方,那么应该是最高位为1,其余位为0,所以如果x&(x-1) == 0的话,说明x是2的n次方
#include<iostream>
using namespace std;
void judge(int x) //判断是否为2的n次方
{
if(0 == (x&(x-1)))
{
cout <<x << "是2的n次方\n";
}
else
{
cout <<x << "不是2的n次方\n";
}
}
int num_of_1(int x) //判断2进制数中1的个数
{
int count = 0;
while(x)
{
count ++;
x = x & (x-1);
}
cout << "The sum of 1 is "<<count<<endl;
return count;
}
int main()
{
int n;
while(1)
{
cin >> n;
judge(n);
num_of_1(n);
cout << endl;
}
return 0;
}