题目:判断一个整数表示为二进制数时,二进制位为1的数目
其中一种简单算法的基本思想:
设整数X,则X&(X-1):即把X的二进制表示的最右边的1设为0,因此循环二进制1的数目的次数即能使的X变为全0,而循环的次数即为其中1的数目。
#include <iostream>
using namespace std;
int bit_Count(int X){
int count=0;
while(X!=0){
++count;
X=X&(X-1);
}
return count;
}
void main(){
int X ;
cout<<"X :";
cin>>X;
cout<<"The number of i in X is:"<<bit_Count(X)<<endl;
}
注意以上的逆命题不成立。
该题的其他更优算法见:http://blog.csdn.net/wangjun_1218/article/details/4464129