首页 > 其他 > 详细

leetcode 191 位1的个数

时间:2019-04-17 12:49:49      阅读:95      评论:0      收藏:0      [点我收藏+]

 技术分享图片

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

技术分享图片

 

对无符号整型的难度实际上不高,只需要不断右移与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;
    }
};

 

leetcode 191 位1的个数

原文:https://www.cnblogs.com/joelwang/p/10722639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!