

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
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
- Related Questions & Answers
- Python Program to Convert Gray Code to Binary
- Python Program to Convert Binary to Gray Code
- Gray Code in C++
- 8085 program to convert gray to binary
- Binary to Gray code using recursion in C program
- What is Gray code?
- 8085 program to convert binary numbers to gray
- Conversion of Binary to Gray Code
- Conversion of Gray Code to Binary
- C Program to convert a given number to words
- 8085 code to convert binary number to ASCII code
- Python Program for How to check if a given number is a Fibonacci number?
- Python Program for Efficient program to print all prime factors of a given number
- Return a description for the given data type code in Python
- Write a Python code to combine two given series and convert it to a dataframe
Advertisements