LeetCode: Number Of One Bits

LeetCode: Number Of One Bits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class NumberOfOneBits {

// you need to treat n as an unsigned value
public int hammingWeight(long n) {
int weight = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1<<i)) != 0) {
weight++;
}
}
return weight;
}

@Test
public void test() {
System.out.println(hammingWeight(2147483648L));
}
}