·
·
·
·
·
·
·
·
[0][1][2][3][4][5][6][7]
DP on the last bit
▸1def countBits(n):2 dp = [0] * (n + 1)3 for i in 1..n:4 # i>>1 drops the last bit (already counted)5 # i&1 adds that dropped bit back6 dp[i] = dp[i >> 1] + (i & 1)7 return dp
state
- n7
- recurrencedp[i] = dp[i>>1] + (i & 1)