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

这篇博客介绍了三种方法来计算一个32位无符号整数中1的个数。第一种是利用C++的内置函数`__builtin_popcount`。第二种是通过位运算逐个消除最右边的1。第三种是SWAR算法,通过位运算高效地统计1的数量。这些技巧在计算机科学和算法优化中很有用。
摘要由CSDN通过智能技术生成

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值