Neat DP problem to go.
from math import * class Solution(object): def countBits(self, num): ret = [0] for i in range(1, num + 1): if i & 1: # odd ret += [ret[-1] + 1] else: prev = i - 1 trailing1s = (i | prev) - i cnt = int(math.log(trailing1s + 1, 2)) ret += [ret[-1] + 1 - cnt] return ret
If you don‘t like log(), you can use lookup table.
时间: 2024-10-14 08:41:47