LeetCode 剑指Offer 15.二进制中1的个数

LeetCode 剑指Offer 15.二进制中1的个数


问题描述

在这里插入图片描述

简要思路

使用 lowbit(n) = n & -n 取第一个 1 的思想。

代码

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

猜你喜欢

转载自blog.csdn.net/qq_45438600/article/details/116998438