剑指 Offer 15. 二进制中1的个数
![image-20210131191417756](C:\Users\peekapoo\AppData\Roaming\Typora\typora-user-images\image-20210131191417756.png)
666
这个用c++就很容易的【粗糙写法】:
int hammingWeight(uint32_t n) {
int res = 0;
while(n != 0){
if(n & 1) res++;
n >>= 1;
}
return res;
}
利用 n&(n-1)
:
int hammingWeight(uint32_t n) {
int res = 0;
while(n != 0){
res ++;
n = n&(n-1);
}
return res;
}