An industrial rotary dial has 2^b discrete positions. To minimize misreads as the dial turns, each position is encoded with a b-bit reflected Gray code, constructed so that moving between any two consecutive positions changes exactly one bit.
The standard reflected Gray code sequence for b bits is built recursively: the 1-bit sequence is [0, 1]; the (k+1)-bit sequence is formed by taking the k-bit sequence, appending its own reverse with the new leading bit set to 1 on the appended half (and 0 on the original half).
Given b and a 0-indexed position k (0 \le k < 2^b), report the decimal value of the Gray code assigned to position k.
Line 1: two space-separated integers b k.
A single integer: the decimal value of the b-bit reflected Gray code at position k.
Example 1
Input
3 5
Expected
7
Explanation
For a 3-bit rotary encoder, the reflected Gray-code sequence is 0,1,3,2,6,7,5,4; position 5 has value 7.
Example 2
Input
2 0
Expected
0
Explanation
Position 0 is always encoded as 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →