Gray Code
An n-bit gray code sequence is a sequence of 2^n integers where:
- Every integer is in the inclusive range
[0, 2^n - 1]. - The first integer is
0. - An integer appears no more than once in the sequence.
- The binary representation of every pair of adjacent integers differs by exactly one bit.
- The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.
Example 1
Input
n = 2Output
[0,1,3,2]The sequence is valid because adjacent binary values differ by exactly one bit, and the last value
10 also differs from the first value 00 by exactly one bit.Example 2
Input
n = 1Output
[0,1]The sequence starts with 0 and the two 1-bit values differ by exactly one bit, including between the last and first values.
Constraints
- 1 <= n <= 16