可以用移位运算来写,这样的问题在于,负数,c++中的右移是算数右移,(高位补 1),而不是逻辑右移(高位补 0)。n永远不会变成 0,而是会一直保持 -1。
// 错误的示例
int NumberOf1(int n) {
// write code here
int cnt = 0;
while(n != 0){
if((n & 0x1) == 1){
cnt++;
}
n = n >> 1;
}
return cnt;
}
解决方法,可以固定只检查32位;
int NumberOf1(int n) {
int cnt = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) { // 检查第i位是否为1
cnt++;
}
}
return cnt;
}
还有一种使用std::bitset的方法。
int NumberOf1(int n) {
return bitset<32>(n).count(); //统计32位中有多少位是1
}
bitset的一些用法:
bitset<8> bitset2(12); //长度为8,二进制保存,前面用0补充
string s = "100101";
bitset<10> bitset3(s); //长度为10,前面用0补充
char s2[] = "10101";
bitset<13> bitset4(s2); //长度为13,前面用0补充
cout << bitset1 << endl; //0000
cout << bitset2 << endl; //00001100
cout << bitset3 << endl; //0000100101
cout << bitset4 << endl; //0000000010101
bitset<8> foo ("10011011");
cout << foo.count() << endl; //5 (count函数用来求bitset中1的位数,foo中共有5个1
cout << foo.size() << endl; //8 (size函数用来求bitset的大小,一共有8位
cout << foo.test(0) << endl; //true (test函数用来查下标处的元素是0还是1,并返回false或true,此处foo[0]为1,返回true
cout << foo.test(2) << endl; //false (同理,foo[2]为0,返回false
cout << foo.any() << endl; //true (any函数检查bitset中是否有1
cout << foo.none() << endl; //false (none函数检查bitset中是否没有1
cout << foo.all() << endl; //false (all函数检查bitset中是全部为1