BITS-P3

The next number with as many 1s

Practice 3 of 5Bit manipulation10 tests

The problem

Return the smallest whole number bigger than x that has the same number of 1 bits as x.

next_same_ones(6)      # 9:  110 -> 1001
next_same_ones(7)      # 11: 111 -> 1011
next_same_ones(156)    # 163: 10011100 -> 10100011

Limits

  • x is at least 1, with up to about 100,000 bits.
  • The answer can be very far from x (for 2 ** 40 - 1 it is about 550 billion bigger), so trying x + 1, x + 2, … is too slow. Build the answer from the bits of x.

Builds on BITS-3 Masks and the lowest 1 bit.

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.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2OneNot run
3A run at the bottomNot run
4A run with zeros belowNot run
5The lesson's exampleNot run
6Ten in a rowNot run
71 to 64Not run
8Forty 1s in a rowNot run
9A run in the middleNot run
10A huge numberNot run