BITS-P2

From Gray code

Practice 2 of 5Bit manipulation10 tests

The problem

The Gray code of a whole number n is n ^ (n >> 1) (lesson 2). Given a Gray code g, return the n it came from. There is always exactly one.

from_gray(6)     # 4, because 4 ^ 2 == 6
from_gray(0)     # 0
from_gray(7)     # 5: 101 ^ 010 == 111

Limits

  • g is 0 or more, with up to 1,000,000 bits. The two biggest tests have 2 seconds each.
  • A loop that shifts g one place at a time is too slow for a million bits: each shift copies the whole number.

Builds on BITS-2 Bitwise operators.

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
2ZeroNot run
3OneNot run
4The 3-bit orderNot run
5All 4-bit codesNot run
6A single 1 at the topNot run
7Alternating bitsNot run
8Round trip up to 3,000Not run
9A million bitsNot run
10A million onesNot run