Number of 1 Bits

来源:互联网 发布:淘宝账户永久无法注销 编辑:程序博客网 时间:2024/06/05 22:32

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.

Bit Manipulation

思路很简单:(4ms)

    int hammingWeight(uint32_t n) {        int count = 0;while (n){if (n % 2)count++;n /= 2;}return count;    }
思路:(4ms)

位运算

    int hammingWeight(uint32_t n) {        int count = 0;while (n){if (n & 1)count++;<span style="white-space:pre"></span>//count += n & 0x1;n = n >> 1;//n >>= 1;}return count;    }
思路:(8ms)

位运算的扩展;

容易想到的是不管是多少个1,都要循环执行32次;

巧妙解法:将循环次数减少到与1的个数相同。利用的性质就是本身n相与n-1。

     int hammingWeight(uint32_t n) {        <span style="white-space:pre"></span>int count = 0;while (n){n = n & (n - 1);count++;}return count;    }
总结:最后一种解法效率反而更低。


0 0