FunctionRacerProblemsRace

Next Gray Code

MediumBitsPython, JavaScript, TypeScript, Java, C++

The bits bit reflected Gray code is the list of the numbers from 0 to 2**bits - 1 in which position i holds i ^ (i >> 1), so neighbouring entries differ in exactly one bit. You are given an entry g of that list. Return the entry that comes right after g. The list wraps around: the entry after the last one is the first one, 0.

Example 1

g 1
bits 2
returns 3

The 2 bit Gray code is 0, 1, 3, 2; after 1 comes 3.

Example 2

g 2
bits 2
returns 0

2 is the last entry of 0, 1, 3, 2, so the list wraps around to 0.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Bits problems