直接使用gcc内建函数:
class Solution {
public:
int hammingWeight(uint32_t n) {
return __builtin_popcount(n);
}
};
自己写判断
方法一:
逐个移位判断
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while (n) {
cnt += n & 1;
n >>= 1;
}
return cnt;
}
};
方法二:
通过与自己低一位的数 & 操作来获取1的个数,因为低一位的数,最左边的1的位都相等
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while (n) {
n &= n - 1;
++cnt;
}
return cnt;
}
};