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.
-
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
它是有规律地重复的
class Solution(object): def countBits(self, num): if num == 0: return [0] res = [0] bit = 0 temp = num while temp > 0: temp /= 2 bit += 1 #print bit for i in xrange(bit-1): t_res = [] for j in res: t_res.append(j+1) res = res + t_res #print res for i in res[:(num - pow(2,bit-1))+1]: res.append(i+1) return res

本文介绍了一种算法,该算法可以计算从0到给定数字范围内所有整数二进制表示中1的数量,并返回这些数量组成的数组。讨论了如何以线性时间复杂度实现这一目标。
157

被折叠的 条评论
为什么被折叠?



