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
xis at least 1, with up to about 100,000 bits.- The answer can be very far from
x(for2 ** 40 - 1it is about 550 billion bigger), so tryingx + 1,x + 2, … is too slow. Build the answer from the bits ofx.
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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
10 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | One | Not run | |
| 3 | A run at the bottom | Not run | |
| 4 | A run with zeros below | Not run | |
| 5 | The lesson's example | Not run | |
| 6 | Ten in a row | Not run | |
| 7 | 1 to 64 | Not run | |
| 8 | Forty 1s in a row | Not run | |
| 9 | A run in the middle | Not run | |
| 10 | A huge number | Not run |