image.png
(图片来源https://leetcode-cn.com/problems/number-of-1-bits/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-23 | 0 |
public int hammingWeight(int n) {
int res = 0;
while(n != 0) { // 不是n >= 0, 而是 n != 0
if((n&1) == 1) {
res ++;
}
// n >>= 1; // >> 右移,如果使用,则符号位也会被移动。如果输入为-3,每次右移高位都会补1(负数),导致死循环
n >>>= 1; // >>> 无符号右移
}
return res;
}
网友评论