Given an integer
n
, return an arrayans
of lengthn + 1
such that for eachi
(0 <= i <= n
),ans[i]
is the number of1
's in the binary representation ofi
.
class Solution:
def countBits(self, n):
res = []
for i in range(n + 1):
# format(i, 'b') --> convert an integer to a binary string without prefix
res.append(format(i, 'b').count('1'))
return res