CodeArchon

easyBit ManipulationApple

Popcount Table

A profiler builds a lookup table of popcount(i) for i in [0, n].

Given an integer n, return an array ans of length n + 1 such that ans[i] is the number of 1 bits in the binary representation of i.

Choose approach

0
0
half
1
1
i
2
2
3
3
4
4
5
5
Mappopcount
0→0
1→1
1/5
Narrationstep 1 of 5

dp[1] = dp[0] + (1 & 1) = 1.

1def countBits(n):
2 dp = [0] * (n + 1)
3 for i in range(1, n + 1):
4 dp[i] = dp[i >> 1] + (i & 1)
5 return dp
Variables
i=1
value=1

How to think about it

  1. Shift-right loses only the LSB.
  2. Each entry O(1) given its predecessor.

Edge cases to catch in interview

  • n = 0 -> [0].
  • Powers of two -> 1.

Examples

Example 1[0,1,1]
{"n":2,"values":[0,1,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed