方法1:位运算
时间复杂度:$O(logN)$
空间复杂度:$O(1)$
解题思路
https://leetcode.cn/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode-solution-jnwf/
Java 代码
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 - 1;
res++;
}
return res;
}
}