题目
题解
这个题,可以直接参考 190. 颠倒二进制位
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int cnt = 0;
for (int i = 0; i < 32; i++) {
cnt += n >>> i & 1;
System.out.println(n >>> i & 1); // 无符号右移
}
return cnt;
}
}
评论区一些比较好的解法
Java API
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}