题目描述:
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].
解题思路:
这道题目可以使用动态规划的思想,每个整数与比他小一的整数的二进制形式相比,小一的数从右往左,第一个为0的位置替换为1,该位置后边的1全部换为0,则为大一的数。所以,如果将这两个数相与,得到的结果值拥有一的个数加上1就是该数拥有1的个数了。
代码:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};