原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn1m0i/
解法一:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n = n >>> 1;
}
return count;
}
}
思路:按位遍历n,每一次遍历和1进行按位与运算,统计1出现的次数,>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0