Member-only story
Leetcode 191: number of 1 bits
In this Leetcode question, we are asked to count and return the number of 1s in the bit representation of 32-bit integers.
Essentially, the problem is quite simple to solve, we can look bit by bit by checking (n & 1)
and divide n
by 2, with bitwise op n >>= 1;
.
However, it get slightly more complicated with negative numbers and the 2-complement representation. In the 2 complement binary representation, if we take a positive integer n
, flipping every single bit will result in -(n+1)
. The reason it is not -n
is that however it would be simpler, flipping all the bits for 0
would result in 0
and that is not acceptable to have 2 different representations of the same number for practical purpose.
To solve the problem in the negative case. I flipped n
to its positive representation and counted the inverse, that is I started with 32 1s
and each time I encounter a 1 in the complement representation I remove 1 from the final result.
Here is the full solution:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
if (n < 0) {
n = - n - 1;
res = 32;
while (n != 0) {
if ((n & 1) != 0) {
res--;
}
n >>= 1…