A rotary encoder emits positions using the standard reflected binary Gray code (consecutive positions differ in exactly one bit). Each physical position k (starting from 0) produces the code g = k XOR (k >> 1).
Given a code value g that the encoder produced, recover the position index k, i.e. the unique non-negative integer such that k XOR (k >> 1) = g.
Line 1: an integer g.
A single integer: the position index k that maps to the Gray code g.
Example 1
Input
7
Expected
5
Explanation
The Gray code sequence is 0,1,3,2,6,7,5,4; the value 7 appears at position 5, and indeed 5 XOR 2 = 7.
Example 2
Input
0
Expected
0
Explanation
Position 0 maps to code 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 →