leetcode 191 位1的个数 随笔 第1张

可参考博客:https://www.cnblogs.com/AndyJee/p/4630568.html,这个对本问题讨论比较详细,本文只针对leetcode答案和剑指offer答案;

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

leetcode 191 位1的个数 随笔 第2张

 

对无符号整型的难度实际上不高,只需要不断右移与1取与就可以了,代码如下:

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

但是对于有符号就比较麻烦了,因为负数采用补码,右移会在左边补1所以采用直接右移会死循环,但是有个小技巧,采用x&(x-1)可以清楚最低位的1;

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

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄