Lit Lamps on a Binary Counter

Easy · Bits & Math · about 10 min

A display shows a number in binary with a row of lamps: a lamp is lit for every 1 bit. The counter goes from 0 up to n.

Return a list of length n + 1 whose entry i is the number of lit lamps when the counter shows i.

  • 0 <= n <= 100000.
  • Try to compute each entry from an earlier one instead of counting bits from scratch.

Examples:

lit_bits_up_to(5) → [0, 1, 1, 2, 1, 2]

lit_bits_up_to(0) → [0]

Hints

  • Shifting i right by one drops its last bit. Which number do you get, and is it smaller than i?
  • The dropped bit is i AND 1. Add it to the count of the shifted number.
  • Remember the list includes n itself, so it has n + 1 entries.

Learn the pattern first: the Bits & Math lesson.

More Bits & Math problems