191. Number of 1 Bits

Leetcode link

解题思路

本题要求我们计算一个 32 位 unsigned int 中 1 的个数

主要考察点事位运算,我们可以用 n &= n - 1 来减少最后一位的 1

只需要不断的减少直到 n 最后为 0,减少的次数就是 1 的次数

C++

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

results matching ""

    No results matching ""