注意的点:
这道题可以用短除法解决,短除法可以用于将一个数化为多少进制的数,在每次除法中,余数代表了从高位到低位的二进制的数。例如:
短除法的递归写法:
def duanchu(x):
if x == 0: return ''
return duanchu(x // 2) + str(x % 2)
解法一:bin()函数转换法
class Solution:
def countBits(self, n: int) -> List[int]:
ans = list(range(n+1))
for i in range(n+1):
ans[i] = len(bin(i)[2:].split('1')) - 1
return ans
解法二:短除法
class Solution:
def countBits(self, n: int) -> List[int]:
def duanchu(x):
if x == 0: return 0
return duanchu(x // 2) + (x % 2) if x % 2 == 1 else duanchu(x // 2)
ans = []
for i in range(n+1):
ans.append(duanchu(i))
return ans