Open In App

Binary to Gray code using recursion

Last Updated : 17 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given the Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code. Assume that the binary number is in the range of integers. For the larger value, we can take a binary number as string.

Note: In Gray Code, consecutive numbers differ by only one bit.

Examples: 

Input: 1001 
Output: 1101
Explanation: The Gray Code for binary 1001 is 1101

Input: 11
Output: 10
Explanation: 11 -> 10

To convert a binary number to Gray Code, check if the last two bits are the same or different. If they are the same, continue without change; otherwise, add 1 to the result. The process is recursive: if n = 0, Gray Code is 0; if the last two bits differ, append 1 and call the function on n/10; otherwise, append 0 and recurse.

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))
CPP
#include <bits/stdc++.h>
using namespace std;

int binary_to_gray(int n)
{
    if (!n)
        return 0;

    // Taking last digit
    int a = n % 10;

    // Taking second last digit
    int b = (n / 10) % 10;

    // If last digit are opposite bits
    if ((a && !b) || (!a && b))
        return (1 + 10 * binary_to_gray(n / 10));

    // If last two bits are same
    return (10 * binary_to_gray(n / 10));
}

// Driver Function
int main()
{
    int binary_number = 1011101;

    printf("%d", binary_to_gray(binary_number));
    return 0;
}
Java Python C# JavaScript

Output
1110011

Time Complexity: O(log(n)), Traverse through all the digits, as there are log(n) bits.
Auxiliary Space: O(log(n)), due to recursive function calls stored in the call stack.




Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg