Skip to main content
2 of 2
Fixed link in header
emanresu A
  • 44.4k
  • 5
  • 101
  • 240

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 expression bin(2**n + i//2 ^ i) calculates the Gray code:
    • 2^n is added to i//2, effectively shifting i 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 the n-bit Gray code

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'

Try it online!