Given Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code.
Input : 1001 Output : 1101 Input : 11 Output : 10
In gray code, only one bit is changed in 2 consecutive numbers.
binary_to_grey(n) if n == 0 grey = 0; else if last two bits are opposite to each other grey = 1 + 10 * binary_to_gray(n/10)) else if last two bits are same grey = 10 * binary_to_gray(n/10))
Below is implementation of above approach :
Assume that the binary number is in the range of integer. For larger value we can take binary number as string.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Code Converters - Binary to/from Gray Code
- Gray to Binary and Binary to Gray conversion
- Decimal Equivalent of Gray Code and its Inverse
- Decimal to binary number using recursion
- Decimal to Binary using recursion and without using power operator
- Find Maximum Level Sum in Binary Tree using Recursion
- Find the node with maximum value in a Binary Search Tree using recursion
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Generate n-bit Gray Codes | Set 2
- Generate n-bit Gray Codes
- A backtracking approach to generate n bit Gray Codes
- Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion
- Find the value of ln(N!) using Recursion
- Tail Recursion