Leetcode ☞ 191. Number of 1 Bits(hamming weight)

191. Number of 1 Bits

My Submissions
Question
Total Accepted: 77196  Total Submissions: 205545  Difficulty: Easy

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.









我的AC(4ms):

<span style="font-size:18px;">int hammingWeight(uint32_t n) {
    int max = log10(n) / log10(2) + 1, count = 0;
    max = (max > 31) ? 31 : max;
    uint32_t yo;
    for (int i = 0 ; i <= max ; i++){
        yo = 1 << i | n;
        if (yo == n)
            count++;
    }
    return count;
}</span>
分析:

先求log来求出二进数的最高位,节省循环。不过不管它,固定循环次数为32,也是4ms。

循环最多到1<<31,即1后面31个零。


下面这个更简洁:

int hammingWeight(uint32_t n) {
    int count = 0;

    for (int i = 0 ; i < 32 ; i++){
        if ((n & 1) == 1)
            count++;
        n >>= 1;
    }
    return count;
}


最后贴一个比较6的新奇解法:

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

用例子解释:

输入n=11(1011)。


循环执行一次:n = 1011 & 1010 = 1010。【把低位1去掉】

循环执行二次:n = 1010 & 1001 = 1000。【把低位1去掉】

循环执行三次:n = 1000 & 0111 = 0000。【把高位1去掉】


n = 0,结束,循环次数即为count=3。

你可能感兴趣的:(Leetcode ☞ 191. Number of 1 Bits(hamming weight))