题目链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
解题思路:
每次将当前n与其最右边的位数(n & 0x1)相与&,判断最左边是否为1,然后加到counter。
然后就把 n>>>1 右移一位,然后继续上面的过程
代码:
public class Solution {
public int hammingWeight(int n) {
int counter = 0;
while (n != 0) {
counter += n & 0x1;
n = n >>> 1;
}
return counter;
}
}