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、It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
2、Space complexity should be O(n).
3、Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
解:如果直接一个个数字辗转相除求余计算的话时间复杂度就为O(n*sizeof(integer)),可以发现,对于二进制表示中1的个数,由于是连续的自然数
组一:
0:0000
1:0001
组二:
2:00 1 0
3:00 1 1
比组一刚好每一个多了一个‘1’(即第二位的‘1’)
组四:
4:0 1 00
5:0 1 01
6:0 1 10
7:0 1 11
把组一组二合起来看做组3,则组四每一个都比组三对应的多一个‘1’(即第3位的‘1’)
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
int count = 0;
if(num == 0)
return res;
//每次取2的幂数个数
for(int k = 0; k < 100000; k++)
for(int i = 0; i < pow(2,k); i++)
{
int nowRes = res[i] + 1;
res.push_back(nowRes);
count++;
if(count == num)
return res;
}
}