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:
Let us see the following implementation to get better understanding:
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))