剑指 Offer -------- 二进制中1的个数

在这里插入图片描述

思路:
这道题有很多种做法,最简单的就是循环遍历32位,还有一种高效的做法就是利用lowbit去做,lowbit返回值表示元素的二进制中最后一个1的数值,哪怕是负数,他也会计算所有位的,包括符号位。

代码:

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

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/115083599
今日推荐