以前写的计算整数的二进制中包含1的数量的函数真是太弱了。。
今天在书上看到的一个简单方法:
int fun(int x)
{
int count = 0;
while(x)
{
count++;
x = x&(x-1);
}
return count;
}
int main()
{
cout<<fun(9999)<<endl; //9999:10011100001111
return 0;
}
以前写的计算整数的二进制中包含1的数量的函数真是太弱了。。
今天在书上看到的一个简单方法:
int fun(int x)
{
int count = 0;
while(x)
{
count++;
x = x&(x-1);
}
return count;
}
int main()
{
cout<<fun(9999)<<endl; //9999:10011100001111
return 0;
}