力扣 191. 位1的个数 位运算

https://leetcode-cn.com/problems/number-of-1-bits/
在这里插入图片描述
思路一:利用C++的内置函数。

class Solution {
    
    
public:
    int hammingWeight(uint32_t n) {
    
    
        return __builtin_popcount(n);
    }
};

思路二:利用位运算性质,每次把末尾的1去掉。

class Solution {
    
    
public:
    int hammingWeight(uint32_t n) {
    
    
        int ans=0;
        while(n)
        {
    
    
            ++ans;
            n&=(n-1);
        }
        return ans;
    }
};

思路三:SWAR算法“计算汉明重量”,不多说了,自己百度看吧。

class Solution {
    
    
public:
    int hammingWeight(uint32_t n) {
    
    
        n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F);
        n = (n * (0x01010101) >> 24);
        return n;
    }
};

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/115075041