题目
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
解题思路
对于一个数i
转换成二进制之后1的个数,如果i
是偶数,则和i/2
的个数相同,如果i
是奇数,则为i/2
的个数加1
代码
class Solution:
def countBits(self, num: int) -> List[int]:
res = [0] * (num + 1)
for i in range(num + 1):
res[i] = res[i >> 1] + (i & 1)
return res