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:
- If n=0 then gray=0.
- Else if the last two bits are opposite to each other then gray = 1 + (10 * binaryToGray(n/10)).
- Else if the last two bits are same then gray = 10 * binaryToGray(n/10)
Below is the implementation of the above approach.
Java
import java.io.*;
class GFG {
public static int binaryToGray( int n)
{
if (n == 0 ) {
return 0 ;
}
int a = n % 10 ;
int b = (n / 10 ) % 10 ;
if ((a & ~b) == 1 || (~a & b) == 1 ) {
return ( 1 + 10 * binaryToGray(n / 10 ));
}
return ( 10 * binaryToGray(n / 10 ));
}
public static void main(String[] args)
{
int binaryNumber = 11010001 ;
int result = binaryToGray(binaryNumber);
System.out.println( "Gray Code is " + result);
}
}
|
OutputGray Code is 10111001
Approach #2: Large Binary Numbers
Algorithm:
- Take input in string format.
- Pass current pointer in a recursive function.
- Store XOR of i’th and (i-1)th bit into array.
- Return the array at the end of recursion.
Below is the implementation of the above approach.
Java
import java.io.*;
class GFG {
public static char xor( char a, char b)
{
if (a == b)
return '0' ;
else
return '1' ;
}
public static char [] ans( char [] kp, String str, int i)
{
if (i == str.length())
return kp;
kp[i] = xor(str.charAt(i), str.charAt(i - 1 ));
i++;
return ans(kp, str, i);
}
public static void main(String args[])
{
String str = "01001" ;
char [] kp = new char [str.length()];
kp[ 0 ] = str.charAt( 0 );
ans(kp, str, 1 );
System.out.print( "Gray Code is " );
for ( char i : kp)
System.out.print(i + "" );
}
}
|
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)