程式語言 - LeetCode - C++ - 338. Counting Bits



題目:


解答:

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> r(n + 1, 0);

        for (int i = 0; i <= n; i++) {
            int v = i;

            for (int j = 0; j < 64; ++j) {
                r[i] += (v & 1);
                v >>= 1;
            }
        }

        return r;
    }
};