Program to convert gray code for a given number in python

Gray code is a binary numeral system where consecutive numbers differ by exactly one bit. For example, the gray code sequence starts as: 000, 001, 011, 010, 110, 111, 101, 100. Given a number n, we need to find the nth gray code in decimal representation.

The key insight is that gray codes follow a recursive pattern where we can find the nth gray code by determining the highest power of 2 less than or equal to n, then recursively solving for the remaining part.

Algorithm Steps

To convert a number to its corresponding gray code position:

  • If n equals 0, return 0
  • Find the largest power of 2 that is ? n
  • Use recursion: gray_code(n) = power_of_2 + gray_code(2 × power_of_2 − n − 1)

Example

Let's implement the solution to find the gray code for a given number ?

class Solution:
    def solve(self, n):
        if n == 0:
            return 0
        
        # Find the largest power of 2 less than or equal to n
        x = 1
        while x * 2 <= n:
            x *= 2
        
        # Recursive formula for gray code
        return x + self.solve(2 * x - n - 1)

# Test the solution
ob = Solution()
n = 12
result = ob.solve(n)
print(f"Gray code for {n} is: {result}")
Gray code for 12 is: 10

Step-by-Step Explanation

For n = 12, let's trace through the algorithm:

def trace_gray_code(n, depth=0):
    indent = "  " * depth
    print(f"{indent}Finding gray code for n={n}")
    
    if n == 0:
        print(f"{indent}Base case: n=0, return 0")
        return 0
    
    x = 1
    while x * 2 <= n:
        x *= 2
    print(f"{indent}Largest power of 2 <= {n} is {x}")
    
    recursive_input = 2 * x - n - 1
    print(f"{indent}Recursive call with: 2*{x} - {n} - 1 = {recursive_input}")
    
    recursive_result = trace_gray_code(recursive_input, depth + 1)
    result = x + recursive_result
    print(f"{indent}Result: {x} + {recursive_result} = {result}")
    
    return result

# Trace the execution
trace_gray_code(12)
Finding gray code for n=12
Largest power of 2 <= 12 is 8
Recursive call with: 2*8 - 12 - 1 = 3
  Finding gray code for n=3
  Largest power of 2 <= 3 is 2
  Recursive call with: 2*2 - 3 - 1 = 0
    Finding gray code for n=0
    Base case: n=0, return 0
  Result: 2 + 0 = 2
Result: 8 + 2 = 10

Alternative Implementation Using Built-in Method

Python provides a direct way to convert binary to gray code using XOR operations ?

def binary_to_gray(n):
    """Convert a number to its gray code equivalent"""
    return n ^ (n >> 1)

def find_nth_gray_code(n):
    """Find the nth number in gray code sequence"""
    # This is the mathematical approach
    if n == 0:
        return 0
    x = 1
    while x * 2 <= n:
        x *= 2
    return x + find_nth_gray_code(2 * x - n - 1)

# Test both methods
numbers = [0, 1, 2, 3, 4, 5, 12]
print("n\tNth Gray Code\tBinary?Gray")
print("-" * 35)

for num in numbers:
    nth_gray = find_nth_gray_code(num)
    bin_to_gray = binary_to_gray(num)
    print(f"{num}\t{nth_gray}\t\t{bin_to_gray}")
n	Nth Gray Code	Binary?Gray
-----------------------------------
0	0		0
1	1		1
2	3		3
3	2		2
4	6		6
5	7		7
12	10		8

Conclusion

The recursive approach finds the nth gray code by identifying the largest power of 2 and applying the mathematical relationship. For n=12, the gray code is 10, which represents the 12th position in the gray code sequence.

Updated on: 2026-03-25T12:48:12+05:30

997 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements