1535. Gray Code Index

Easy1.5 points estimatedBit ManipulationMaths

The reflected binary Gray sequence lists the non-negative integers so that consecutive entries differ in exactly one bit. Its i-th entry (counting from i = 0) is i ^ (i >> 1), so the sequence starts 0, 1, 3, 2, 6, 7, 5, 4, 12, ...

Given a value code that appears in this sequence, return its position i, that is, the unique non-negative integer with i ^ (i >> 1) == code. Every non-negative integer appears exactly once, so the answer always exists and is unique.

Input: one integer code. Output: one integer. Decode it by prefix-XORing the bits from the top: bit k of the answer is the XOR of bits k and above of code. Time O(log code), space O(1). Note that code can exceed 32 bits.

Example 1

Input:
code = 6
Output:
4
Explanation:

The sequence 0, 1, 3, 2, 6 places 6 at index 4.

Example 2

Input:
code = 2
Output:
3
Explanation:

2 appears at index 3 (3 ^ 1 = 2).

Constraints

0 ≤ code < 250

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(log code)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…