338. Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:

For num = 5 you should return [0,1,1,2,1,2].

思路:返回二进制中1的个数,可以借助已有的结果。ret[i] = ret[i >> 1] + (i & 1);

class Solution {
public:
    vector countBits(int num) {
        vector ret(num+1,0);
        for(int i = 1; i <= num; i++) {
            ret[i] = ret[i >> 1] + (i & 1);
        }
        return ret;
    }
};



你可能感兴趣的:(LeetCode)