Problems > N-th Gray Code

N-th Gray Code

Difficulty: 1300 2000 ms 128 MB

math bitwise

In the reflected Gray code sequence, consecutive values differ in exactly one bit. Print the N-th code (0-indexed: G(0)=0, G(1)=1, G(2)=3, G(3)=2, ...).

Input: one integer N.

Output: G(N) = N ⊕ ⌊N/2⌋.

Constraints:

  • 0 ≤ N ≤ 1018

Sample Tests

Input 1
2
Output 1
3
Input 2
3
Output 2
2

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.