Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-159

Gray Code Sequence

Problem

Return the standard reflected Gray code sequence of length 2 to the n starting from 0.

The i-th value is i XOR (i >> 1), which guarantees that consecutive values differ in exactly one bit. Return [0] for n = 0.

Hint

XOR with the value shifted right one bit converts binary counting into Gray code.

Test cases

case 1
in: [1]
expected: [0,1]
case 2
in: [2]
expected: [0,1,3,2]
case 3
in: [3]
expected: [0,1,3,2,6,7,5,4]
case 4
in: [0]
expected: [0]
Starter codePython
def gray_code(n):
    # Your code here
    pass

4 test cases · run your code against them in the editor