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.
Hint:
You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?
解法1:找规律, O(N)
本题比较简单的解法也是从找规律而来
0 -> 0
1 -> 1
2 -> 10 -> 1
3 -> 11 -> 2
4 -> 100 -> 1
5 -> 101 -> 2
对于偶数i,他的1的个数是i/2的1的个数
杜宇奇数i,他的1的个数是i/的1的个数+1
因为对于一个数除以2的操作就是一个右移操作,而偶数的最低位为0,奇数的最低位为1, 那么右移的时候偶数的1的个数不会变,奇数的1的个数会减少1. 由此写出程序。
解法2: HashMap
观察现象可以发现,每一个数字如果是2的幂次,那么1的个数为1.如果不是,则 = 1 + dp[数字 - 最接近这个数的2的幂次数]
这里dp记录的是每一个数字的1的个数。
|
|
解法3:
观察现象,如果是偶数,则结果和偶数/2一样,如果是奇数,那么是奇数/2 + 1.
|
|