解法一:
十进制转为二进制,统计1的个数
class Solution:
def Ten2Binary(self, x):
res = []
if x == 0:
res = []
while x >= 1:
tempx = x // 2
if x - 2 * tempx == 1:
res.append(x - 2 * tempx)
x = tempx
return len(res)
def countBits(self, n: int) -> List[int]:
result = []
for i in range(n+1):
result.append(self.Ten2Binary(i))
return result
解法二:奇偶性
class Solution:
def countBits(self, n: int) -> List[int]:
result = [0] * (n+1)
for i in range(n+1):
if i & 1 == 0:
result[i] = result[i>>1]
else:
result[i] = result[i-1] + 1
return result