Monday, March 30, 2015

Number of 1 Bits

    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n)
        {
            n &= n - 1;
            ++ res;
        }
        return res;      
    }

"n &= n - 1" is used to delete the right "1" of n. For example:
  • if n = 5 (101), then n-1 = 100, so n & (n-1) = 100, the right "1" is deleted;
  • if n = 6,(110), then n-1 = 101, so n & (n-1) = 100, the right "1" is also deleted;
  • and so on...
So time complexity is O(m), and m is the count of 1's, also m is less than or equal to 32.

No comments:

Post a Comment