題目:輸入一個整數,求該整數的二進制表達中有多少個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;
}