Leetcode 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.


解题思路:

快速法,这种方法速度比较快,其运算次数与输入n的大小无关,只与n中1的个数有关。如果n的二进制表示中有k个1,那么这个方法只需要循环k次即可。其原理是不断清除n的二进制表示中最右边的1,同时累加计数器,直至n为0。

为什么n &= (n – 1)能清除最右边的1呢?因为从二进制的角度讲,n相当于在n - 1的最低位加上1。举个例子,8(1000)= 7(0111)+ 1(0001),所以8 & 7 = (1000)&(0111)= 0(0000),清除了8最右边的1(其实就是最高位的1,因为8的二进制中只有一个1)。再比如7(0111)= 6(0110)+ 1(0001),所以7 & 6 = (0111)&(0110)= 6(0110),清除了7的二进制表示中最右边的1(也就是最低位的1)。


Java code:

// you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int num = 0;
        while(n!=0) {
            n &= n-1;
            num +=1;
        }
        return num;

    }

Reference:

1. https://leetcode.com/discuss/27609/short-code-of-c-o-m-by-time-m-is-the-count-of-1s

2. http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

 

posted @ 2015-09-09 13:11  茜茜的技术空间  阅读(157)  评论(0编辑  收藏  举报