暴力解法:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
ans = []
for i in range(0, num + 1):
n = i
print (n)
if n == 1:
count = 1
else:
count = 0
while n > 1:
count += n % 2
n = n / 2
if n == 1:
count += 1
ans.append(count)
return ans
动态规划:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0] * (num+1)
dp[0] = 0
for i in range(1, num + 1):
if i % 2 == 0:
dp[i] = dp[i/2]
else:
dp[i] = dp[i-1] + 1
return dp