简单移位操作:
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
for(int i = 0; i < 32; ++i){
if(n & 1) ++res;
n >>= 1;
}
return res;
}
};
bieset操作(bieset没有迭代器):
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
bitset<32> a(n);
for(int i = 0; i < 32; ++i){
if(a[i]) ++res;
}
return res;
}
};
或者更直接:
class Solution {
public:
int hammingWeight(uint32_t n) {
return bitset<32>(n).count();
}
};