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].
i如果是偶数,则1的位数和i/2相等,如果是奇数,醉靠近他的一个偶数末尾为0,所以+1就行
c++实现:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> cb(num+1, 0);
if (num > 0) {
cb[1] = 1;
for (int i = 2; i <= num; i++) {
cb[i] = cb[i/2] + cb[i%2];
}
}
return cb;
}
};