publicclassSolution { // you need to treat n as an unsigned value publicinthammingWeight(int n) { intweight=0; while (n != 0) { if ((n & 1) == 1) { weight++; } n >>>= 1; }
return weight; } }
n & (n − 1)
1 2 3 4 5 6 7 8 9 10 11 12
publicclassSolution { // you need to treat n as an unsigned value publicinthammingWeight(int n) { intweight=0; while (n != 0) { // 注意 i 可能为负数,所以此处需要使用不等于 0 判断,而不能使用大于 0 进行判断 weight++; n &= n - 1; }