Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of bits it has (also known as the Hamming weight).
Code
public int hammingWeight(int n) {
int result;
for (; n != 0; n = n & n - 1) result += 1;
return result;
}
Explanation
The trick is to do a bitwise of and . This operation has the effect of flipping the least significant to . Then, answer is the number of times we need to carry out this operation to turn the number to zero.
To see the effect of -ing and , look at the binary representation of the three numbers closely. Notice that after the operation:
- the least significant of , highlighted in pink turns to after the operation;
- the bits to the right of are all ’s;
- the bits to the left of remain the same.
This is the case when is even. Whn is odd, the effect is the same.