Gray Code

Medium · Bit Manipulation · about 15 minutes

Asked at Amazon, Google, Microsoft.

An n-bit Gray code sequence lists all 2ⁿ integers in [0, 2ⁿ − 1], starting at 0, such that consecutive values (including the last and the first) differ in exactly one bit. Return the standard reflected Gray code for n, where the i-th value is i XOR (i >> 1).