Counting Bits
A.题意
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个数
B.思路
这道题目其实就转换一下思维就好,二进制变为2倍就是后面补个0,而如果是补1的话就不能被2整除,所以当数字可以被2整除的时候1的个数是它除以2的数字对应二进制数中1的个数,而不被2整除的时候就是这个数字加上1,于是我们有了递归方程,可以用动态规划实现。
if (i % 2 == 0)
{
ans[i] = ans[i / 2];
} else {
ans[i] = ans[i / 2] + 1;
}
C.代码实现
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num + 1);
if (num == 0)
{
return ans;
}
ans[1] = 1;
for (int i = 2; i <= num; i++)
{
if (i % 2 == 0)
{
ans[i] = ans[i / 2];
} else {
ans[i] = ans[i / 2] + 1;
}
}
return ans;
}
};