方法1.每次消去最右边的1,直到消完为止
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;//最右边的1会退为0,可能会影响该位后一位0变为1,但是&运算没有影响
count++;
}
return count;
}
方法2:把n往右移32次,每次都和1进行与运算
public int hammingWeight(int n) {
int count = 0;
for(int i = 0; i < 32; i++){
if((res & 1) == 1){
count++;
}
res >>>= 1;
return count;
}