求下面函数的返回值(微软)
int func(int x)
{
int count = 0;
while(x)
{
count++;
x = x & (x-1);
}
return (count);
}
自己补充的完整代码:
#include<iostream>
using namespace std;
int func(int x)
{
int count = 0;
while(x)
{
count++;
x = x & (x-1);
}
return (count);
}
int main()
{
int x = 0;
cout<<"Input: ";
cin>>x;
x = func(x);
cout<<"Return: "<<x<<endl;
return 0;
}
运行结果:(思路:将x转化为2进制,看含有的1的个数)
注: 每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。
即:x = 1111, x-1 = 1110, 则 x&(x-1) = 1100.