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.
题目意思是给定一个数字,让你返回一个list。list中是所有小于这个数字的数的二进制形式中1的个数。
这题我有点不爽...这是一个数学问题,我的解法时间复杂度没有符合O(n)的要求,所以我要很不爽地写上三个解法,最后一个符合要求。
第一种,用python库解决:
class Solution(object):
def countBits(self,num):
res=[]
for i in range(num+1):
nbin = bin(i & 0xffffffff)
res.append(nbin.count('1'))
return res
s=Solution()
print(s.countBits(5))
简单明了,位运算。
第二种,手动求解:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res=[]
for i in range(num+1):
count=0
while i>0:
if i%2==1: count+=1
i=i//2
res.append(count)
return res
s=Solution()
print(s.countBits(5))
第三种,既时间复杂度符合O(n)算法:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
iniArr = [0]
if num > 0:
amountToAdd = 1
while len(iniArr) < num + 1:
iniArr.extend([x+1 for x in iniArr])
return iniArr[0:num+1]