求int型正整数在内存中存储时1的个数
求int型正整数在内存中存储时1的个数
http://www.nowcoder.com/questionTerminal/440f16e490a0404786865e99c6ad91c9
求int型正整数在内存中存储时1的个数
位运算
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
cout << n << endl;
return 0;
} 
查看12道真题和解析