leetcode 191 位1的个数

 

可参考博客: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;
    }
};

 

posted @ 2019-04-17 11:56  Joel_Wang  阅读(222)  评论(0编辑  收藏  举报