题目:
解题:用&运算(&运算的规则就是两个1做&运算结果为1,其他为0) ,对于n-1,它的 最右边的 1相比n 变成 0 ,此 1 右边的 0 都变成 1 。
n跟n-1做&运算的时候会消去最右边的一个1,
所以每次消去一个1就计数一次,直到n等于0为止:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res=0;
while(n!=0){
res++;
n=n&(n-1);
}
return res;
}
}