关于 Brian Kernighan 算法,可以查看这篇博客https://www.cnblogs.com/jerryfish/p/15307637.html
它用于将一个二进制数最右边的1变为0
算法核心就是 n & (n-1),其中&就是按位与
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n){
n = n & (n-1); // 不断地删掉最右边的1,直接n变为零
res++;
}
return res;
}
};



