BITS-P4

All the 1 bits up to n

Practice 4 of 5Bit manipulation12 tests

The problem

Write every whole number from 0 to n in binary. Return how many 1 bits there are in all of them together.

ones_upto(5)     # 7: 0, 1, 10, 11, 100, 101
ones_upto(7)     # 12
ones_upto(0)     # 0

Limits

  • n is from 0 to 10¹⁰⁰ (a 1 followed by 100 zeros). Counting the bits of every number is far too slow above a few million.

Builds on BITS-4 Counting bits.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2ZeroNot run
3OneNot run
4Up to 7Not run
5Up to 8Not run
6Every n below 40Not run
7A thousandNot run
8A millionNot run
9A billionNot run
10All 60-bit numbersNot run
1110¹⁸Not run
1210¹⁰⁰Not run