Number of 1 Bits

By | April 11, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

https://leetcode.com/problems/number-of-1-bits/

Write a function that takes an unsigned integer and returns the number of ’1′ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11′ has binary representation 00000000000000000000000000001011, so the function should return 3.

Solution: My initial formula uses n = n & ~(n & (-n)). But there is a better one: n = n & (n – 1).

So we have java code like below:

public int hammingWeight(int n) {
    int ans = 0;
    while (n != 0) {
        n = n & (n - 1);
        ans++;
    }
    return ans;
}

This problem gives condition that it is an unsigned integer. If it is an negative number, neither in Java nor Python, it won’t show up 0 by shifting right.

  • junmin liu

    any explanation behind the solution?