每次把n的最后一位和1做& 假如是1 那么就累计有一位,
然后把n右移一位 注意这里右移用的是unsigned >>> 因为不要考虑最高位的sign
然后while的判断条件一定是 n != 0
In Java we need to put attention on the fact that the maximum integer is 2147483647. Integer type in Java is signed and there is no unsigned int. So the input 2147483648 is represented in Java as -2147483648 (in java int type has a cyclic representation, that means Integer.MAXVALUE+1==Integer.MINVALUE). This force us to use
n!=0
in the while condition and we cannot use
n>0
because the input 2147483648 would correspond to -2147483648 in java and the code would not enter the while if the condition is n>0 for n=2147483648.
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 & 1 );
n = n >>> 1;
}
return res;
}
}