剑指 Offer 15. 二进制中1的个数
题目
剑指 Offer 15. 二进制中1的个数
代码
逐位判断
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n) {
res += n & 1;
n >>= 1;
}
return res;
}
};
\(n\& (n - 1)\)
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n) {
res++;
n &= n - 1;
}
return res;
}
};