Poison

191. Number of 1 Bits

Iterate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int weight = 0;
while (n != 0) {
if ((n & 1) == 1) {
weight++;
}
n >>>= 1;
}

return weight;
}
}
n & (n − 1)
1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int weight = 0;
while (n != 0) { // 注意 i 可能为负数,所以此处需要使用不等于 0 判断,而不能使用大于 0 进行判断
weight++;
n &= n - 1;
}

return weight;
}
}
Reference

191. Number of 1 Bits
剑指 Offer 15. 二进制中1的个数