Python 3, 48 bytes
for i in range(1<<n):print(bin(2**n+i//2^i)[3:])
Explanation:
- The outer loop iterates over numbers from 0 to 2^n - 1
- For each number
i
, the expressionbin(2**n + i//2 ^ i)
calculates the Gray code:- 2^n is added to
i//2
, effectively shiftingi
one position to the right - The XOR operator
^
is used to perform the Gray code transformation - Adding 2^n ensures the resulting binary representation has
n
bits bin()
converts the integer to a binary string[3:]
slices the binary string to remove the prefix '0b', leaving only then
-bit Gray code
- 2^n is added to
Ungolfed:
n = int(input()) # Take input for the number of bits in the Gray code
for i in range(1 << n): # Iterate over numbers from 0 to 2^n - 1
gray_code = bin(2**n + i // 2 ^ i) # Calculate the Gray code for the current number
print(gray_code[3:]) # Print the Gray code excluding the prefix '0b'