
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements