给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
示例 1:
输入: 2
输出: [0,1,1]
示例 2:输入: 5
输出: [0,1,1,2,1,2]1.正常做法,没一个元素做popcount(n=n&(n-1))
2.dp p(x)=p(x/2)+x%2
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
p(x) = p(x/2)+ x mod 2
"""
res = [0 for _ in range(num+1)]
for i in range(1,num+1):
res[i]=res[i>>1] + (i&1)
return res
来源:CSDN
作者:p0ther
链接:https://blog.csdn.net/qq_36328915/article/details/104222777