problem describe:
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.
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
我们可以通过计算二进制的原理来对他进行计算,算出其中含有的1
class Solution {
public:
vector<int> countBits(int num) {
vector<int> a(0);
for(int i=0;i<=num;i++)
{
a.push_back(ans(i));
}
return a;
}
int ans(int num)
{
int count =0;
if(num==0) return 0;
while(num>=1)
{
if(num%2==1)count++;
num=num/2;
}
return count;
}
};
题目提示说有O(n)的解法,看了一下大佬的解法,只能用excellent来形容了(汗)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> a(num+1,0);
for(int i=1;i<=num;++i)
{
a[i]=a[i&(i-1)]+1;
}
return a;
}
};
简洁明了。