Open fockspaces opened 6 months ago
we can further simplify the logic by removing if condition take advantage of i % 2 for determining whether add 1 or not.
class Solution:
def countBits(self, n: int) -> List[int]:
ans = [0] * (n + 1)
for i in range(n + 1):
ans[i] = ans[i // 2] + i % 2
return ans
ans is an array that ans[i] is 1's counts for i's binary representation. we can list some of them: 0: 0 (0) 1: 1 (1) 2: 10 (1) 3: 11 (2) 4: 10 (1)
we found that,