思路:对应数字n的二进制中1的位数是有规律的。0的位数为0。1是2的0次幂,2是2的1次幂。因此,只要是2的幂的数的二进制中1的位数都是1。那么对应地,3的二进制中1的位数就是2的位数加上1的位数;同理,7的二进制中1的位数就是4的位数加上3的位数,使用动态规划得解:dp[n]=dp[n-最近的2的幂]+1,其中1代表的是最近的2的幂本身二进制中包含1个1。
class Solution:
def countBits(self, num: int) -> List[int]:
import math
if num == 0:
return [0]
result = [0]
temp_log = 0
for n in range(1,num+1):
if int(math.log(n,2))==math.log(n,2):
temp_log = int(math.log(n,2))
result.append(result[n-int(math.pow(2,temp_log))]+1)
return result