您的位置:首页 > 其它

IT公司100题-28-整数的二进制表示中1的个数

2014-08-28 22:23 288 查看
问题描述:

输入一个整数n,求n的二进制表示中,一共有多少个1。例如n=8,二进制表示为00001000,二进制表示中有1个1。

分析:
如果一个数n不为0,那么n-1的二进制表示,与n的二进制表示相比,n的二进制表示最右边的1变为0,而最右边的1所对应的0全部变为1。其余位不受影响。
例如:n的二进制表示为****1000,则n-1的二进制表示为****0111,则n&(n-1)的二进制表示为****0000。将n二进制表示中最右边的1去掉了。
将n赋值为n&(n-1),继续循环此操作,直到n为0。

代码实现:

#include <iostream>
using namespace std;

int calc(int num) {
int count;
while(num){
count++;
num = num & (num-1);
}
return count;
}

int main() {
cout << "input n: " << endl;
int n;
cin >> n;
int count = calc(n);
cout << "The num of 1 in " << n << " is: " << count << endl;
return 0;
}


输出:

$ ./a.exe
input n:
11
The num of 1 in 11 is: 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: