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
0half
1
1i
2
23
34
45
5Mappopcount
0→0
1→1
1/5
Narrationstep 1 of 5
dp[1] = dp[0] + (1 & 1) = 1.
Variables
i=1
value=1
How to think about it
- Shift-right loses only the LSB.
- 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