Open In App

Java Program to Convert Binary Code Into Equivalent Gray Code Using Recursion

Last Updated : 11 Sep, 2022
Comments
Improve
Suggest changes
2 Likes
Like
Report

Convert the Binary code of the Number into it's equivalent Gray's code using recursion. Binary is the default way to store numbers, but in many applications, binary numbers are not useful and a variation of binary is needed. Gray code has the property that two successive numbers differ in only one bit and used in K-maps, error correction, and communication.

Examples:

Input:    1101
Output:    1011
Input:    11010001
Output:    10111001

Approach #1: Numbers Under Integer Limit

Algorithm:

  1. If n=0 then gray=0.
  2. Else if the last two bits are opposite to each other then gray = 1 + (10 * binaryToGray(n/10)).
  3. Else if the last two bits are same then gray = 10 * binaryToGray(n/10)

Below is the implementation of the above approach.


Output
Gray Code is 10111001

Approach #2: Large Binary Numbers

Algorithm:

  1. Take input in string format.
  2. Pass current pointer in a recursive function.
  3. Store XOR of i'th and (i-1)th bit into array.
  4. Return the array at the end of recursion.

Below is the implementation of the above approach.


Output
Gray Code is 01101

Time Complexity: O(N), where N is the length of Binary Code.

Auxiliary Space: O(N) if char array kp is considered, otherwise O(1)


Next Article

Similar Reads