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

题目

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

代码

逐位判断

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

\(n\& (n - 1)\)

image

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n) {
            res++;
            n &= n - 1;
        }
        return res;
    }
};
posted @ 2022-04-20 15:53  当惜  阅读(21)  评论(0)    收藏  举报