LeetCode 338-Counting Bits

分析

给每个数循环做x & (x - 1)并计数就是它二进制数中1的个数。

class Solution {
public:
    vector countBits(int num) {
        vector ret;
        for (int i = 0; i <= num; ++i) {
            ret.push_back(count(i));
        }
        return ret;
    }
    
    int count(int x) {
        int ret = 0;
        while (x) {
            x = x & (x - 1);
            ++ret;
        }
        return ret;
    }
};

你可能感兴趣的:(LeetCode 338-Counting Bits)