#include <iostream>
using namespace std;
int func(int x)
{
int countx = 0;
while(x)
{
countx ++;
x = x&(x-1);
}
return countx;
}
int main()
{
cout<<func(7)<<endl;
}
求函数的返回值
实例
0000 0000 0000 0111
0000 0000 0000 0110
0000 0000 0000 0101
0000 0000 0000 0100
0000 0000 0000 0011
求int x中含有1的个数.
下面是模仿
#include <iostream>
using namespace std;
int func(int x)
{
int countx = 0;
while(x)
{
countx ++;
x = x&(x-1);
}
return countx;
}
int funcSame(int x)
{
int countx = 0;
while( x != 0 )
{
if( 1 == x%2 )
countx ++;
x = x/2;
}
return countx;
}
int main()
{
cout<<func(1)<<endl;
cout<<funcSame(9999)<<endl;
}