Problem 353
Gray Code Sequence
Medium · 20 pts · Math, Bit Manipulation, Backtracking
Problem
An N-bit Gray code is an ordering of all 2^N numbers from 0 to 2^N - 1 in which consecutive numbers differ in exactly one bit. Many orderings work, so print the standard reflected Gray code: the i-th number of the sequence (counting from 0) is i XOR (i >> 1). The sequence always starts with 0.
Input
A single integer N.
Output
Print the 2^N numbers of the sequence, separated by spaces.
Constraints
1 <= N <= 12
Example input
2
Example output
0 1 3 2
Explanation
For N = 2 the sequence is 0 1 3 2, which in binary is 00, 01, 11, 10: each step flips exactly one bit.