Gray Code
An n-bit Gray code sequence is a list of 2^n integers where every integer is in [0, 2^n - 1], the sequence starts at 0, each integer appears exactly once, adjacent integers differ in exactly one bit, and the first and last integers also differ in exactly one bit. Given n, return any valid n-bit Gray code sequence.
Open official problem prompt ↗Enumerate all 2^n binary numbers in an order where each step changes only a single bit, forming a cyclic single-bit-change sequence starting at 0.
Turning the dials of a combination lock so that only one wheel clicks by one notch at a time, yet you still visit every possible combination exactly once.
- Input
- n = 2
- Output
- [0, 1, 3, 2]
- Why
- 00 -> 01 -> 11 -> 10 each differ by one bit, and 10 -> 00 (wrap) also differs by one bit.
1 <= n <= 16