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]
.
这道题的意思是要返回所有不大于num的二进制数所含有的1 显然我们可以发现每个2的n次的二进制数所含的1都是一个 而且会重复前面的所有步骤直到再进一位 于是就是说当下的这个数减去不大于它的二的幂后所对应下标的元素 再将这个元素加上一 就是我们要求的这个元素的二进制所含的1的个数
代码如下:
void add(vector<int>&vec,int num){
int x=0;
for(int i=0;;i++)
{
x=pow(2,i);
if(x>num)
{
x=pow(2,i-1);
break;
}
else if(x==num)
{
x=num;
}
else
continue;
}
vec.push_back(vec[num-x]+1);
}
vector<int> countBits(int num) {
vector<int>result;
result.push_back(0);
if(num==0)
{
return result;
}
for(int i=1;i<num+1;i++)
{
add(result,i);
}
return result;
}