class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num+1,0);
for(int i = 1; i < res.size();i++)
res[i] = i%2 + res[i/2];
return res;
}
};
Simple and 4 lines

I like the answer. It makes lot of sense.
I personally did it a bit cheaper way but a dynamic programming is better.
Here is what I did in Python:class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ arr = [] for i in range(num+1): binary = bin(i)[2:] ones = binary.replace("0","") count = len(ones) arr.append(count) return arr