public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
n = n & (n - 1);
res += 1;
}
return res;
}
}
注:
x & x - 1 会把二进制中的最后一个1去掉。这个可以直接记住。