Program to convert gray code for a given number in python


Suppose we have a number n, we have to find the gray code for that given number (in other words nth gray code). As we know the gray code is a way of ordering binary numbers such that each consecutive number's values differ by exactly one bit. Some gray codes are: [0, 1, 11, 10, 110, 111, and so on]

So, if the input is like n = 12, then the output will be 10 as the 12 is (1100) in binary, corresponding gray code will be (1010) whose decimal equivalent is 10.

To solve this, we will follow these steps:

  • Define a function solve() . This will take n
  • if n is same as 0, then
    • return 0
  • x := 1
  • while x * 2 <= n, do
    • x := x * 2
  • return x + solve(2 * x - n - 1)

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution:
   def solve(self, n):
      if n == 0:
         return 0
      x = 1
      while x * 2 <= n:
         x *= 2
      return x + self.solve(2 * x - n - 1)

ob = Solution()
n = 12
print(ob.solve(n))

Input

12

Output

10

Updated on: 26-Nov-2020

540 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements