题目:输入一个整数,求该整数的二进制表达中有多少个1。
例如输入10,由于其二进制表示为1010,有两个1,因此输出2。
答案:
//20130215
#include <iostream>
using namespace std;
int count1(int n);
int main(int argc, char* argv[])
{
int n = 64;
cout<<count1(n);
return 0;
}
int count1(int n)
{
int c = 0;
while (n != 0)
{
n = n & (n - 1);
c++;
}
return c;
}