public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
while(n!=0){
if((n&1)==1)
count++;
n>>>=1;
}
return count;
}
}
使用了>>>而不是>>,>>>是无符号右移,忽略符号位。
可能出错的地方:未给n&1加括号,报bad operand types for binary operator '&'错误
主要是因为==优先级大于&导致的
或者:
return Integer.bitCount(n);
或者:
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0) {
n&= n-1;
count++;
}
return count;
}
把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0,那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。