191.Number of 1 Bits

来源:互联网 发布:java线程池控制并发 编辑:程序博客网 时间:2024/05/17 02:41

问题:
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.

我的解答:

class Solution {public:    int hammingWeight(uint32_t n) {        int count = 0;    for (int i = 0; i < 32; i++)    {        count += n&0x01;        n=n >> 1;     }    return count;    }};

解释:拿到这道题很自然就想到通过移位来计算这里面有多少个1。通过32次与0x01提取最右边的数,看是不是1.
看别人的想法是通过与减一位的数来来计算的。如下

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

解释:
每次n减1,那么原来的n的最右边一个1就变为0,该1右边的所有0变为1.原n与该n-1与了之后,那么最右1及右边的所有位都为0.如
If n = 00101100, then n - 1 = 00101011, so n & (n - 1) = 00101100 & 00101011 = 00101000. Count = 1.

If n = 00101000, then n - 1 = 00100111, so n & (n - 1) = 00101000 & 00100111 = 00100000. Count = 2.

If n = 00100000, then n - 1 = 00011111, so n & (n - 1) = 00100000 & 00011111 = 00000000. Count = 3.

然后循环的次数不用32次,只要循环“1”的个数就够了,因为是判断n是否为0的。n为0即结束

0 0
原创粉丝点击