#338

Counting Bits

Easy Bits + DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For every i from 0 to n, return how many 1-bits i has.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the number of 1-bits for every number from 0 to n.

Why this works: i >> 1 is i without its last bit, and we already know its answer. Add back the last bit with i & 1.

Example: n = 5

0:0  1:1  2:bits[1]+0=1  3:bits[1]+1=24:bits[2]+0=1  5:bits[2]+1=2[0, 1, 1, 2, 1, 2]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Calling a popcount loop for every i — O(n log n). Fine, but the reuse trick is what interviewers look for.