题目:
Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).
思路:
利用mask挨个比较每一位就好了。
代码实现:
class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t mask = 1;
int count = 0;
while (mask){
if (n & mask){
++count;
}
mask <<= 1;
}
return count;
}
};
discuss:
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n){
n &= (n - 1); // 可以消除掉最低位的那一个1
++count;
}
return count;
}
};