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 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Follow up:
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?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
个人认为这道题目的意图就在于寻找规律,因为相邻两个数字的二进制形式是有很大的联系的,请看下面的例子:(2‘1 表示数字2的二进制形式中的1的个数)
二进制数的位数 | 原数字 | 二进制形式 | 1的数字 | 备注 |
---|---|---|---|---|
1 | 0 | 0 | 0 | |
1 | 1 | 1 | 1 | 0‘1 + 1 |
2 | 2 | 10 | 1 | 0‘1 + 1 |
2 | 3 | 11 | 2 | 1‘1 + 1 |
3 | 4 | 100 | 1 | 0‘1 + 1 |
3 | 5 | 101 | 2 | 1‘1 + 1 |
3 | 6 | 110 | 2 | 2‘1 + 1 |
3 | 7 | 111 | 3 | 3’1 + 1 |
4 | 8 | 1000 | 1 | 0’1 + 1 |
4 | 9 | 1001 | 2 | 1‘1 + 1 |
4 | 10 | 1010 | 2 | 2‘1 + 1 |
4 | 11 | 1011 | 3 | 3‘1 + 1 |
4 | 12 | 1100 | 2 | 4‘1 + 1 |
4 | 13 | 1101 | 3 | 5‘1 + 1 |
4 | 14 | 1110 | 3 | 6‘1 + 1 |
4 | 15 | 1111 | 4 | 7‘1 + 1 |
5 | 16 | 10000 | 1 | 0‘1 + 1 |
5 | 17 | 10001 | 2 | 1‘1 + 1 |
5 | 18 | 10010 | 2 | 2‘1 + 1 |
从上表中可以看出,二进制形式长度为i
的数字集合的二进制形式的1
的个数是二进制形式长度<i
的数字集合的二进制形式的1
的个数+1
,这句话有点绕,总之,计算二进制形式长度为2
的2
和3
的二进制中的1
的个数,正是数字0
和1
的二进制中的1
的个数+1
,同样4’1 = 1 + 0'1
,5’1 = 1 + 1'1
,6’1 = 1 + 2'1
,7’1 = 1 + 3'1
。正是如此一种规律。因此可以得出下面的代码:
vector<int> countBits(int num)
{
if(num < 0)return {};
vector<int> result{0};
if(num == 0)return result;
while(true)
{
int cur_size = result.size();
for(int i = 0; i < cur_size; i++)
{
result.push_back(result[i] + 1);
if(result.size() > num)return result;
}
}
return result;
}