题型:二进制
题目:
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]
.
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.
翻译:
给一个数字num,输出0到num间每个数字的二进制的1的个数
下面的时间O(n)和空间O(n)的优化要求
遍历可基本解决。
既然要到O(n),说明最后成型的数组是有规律的
一开始的思路,由于每个2的倍数的数加上自身都是乘2,即1往左一位,那么2^(n-1)到2^n之间的数前一半就是2^(n-2)到2^(n-1)之间的数,后一半就是2^(n-2)到2^(n-1)之间的数加1,0-7的二进制如下
0
1
10 11
100 101 111
1000 1001 1011 1100 1101 1111
则1的数量为:
0
1
1 2
1 2 2 3
1 2 2 3 2 3 3 4
所以就想着每次循环把前面的一组扩一倍然后均加1再拼到ans里
明显费时费力
这里需要细致观察,对于二进制来说,偶数最后一位均是0,奇数均是1,所以偶数右移一位(即除以2)1的数量不变,奇数右移一位1的数量减一,以此递推的方式获取整个数组,即实现了双O(n)
代码:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = [0] * (num + 1)
for i in range(1,num + 1):
if i%2:
ans[i] = ans[(i-1)/2] + 1
else:
ans[i] = ans[i/2]
return ans