VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-convert-binary-code-equivalent-gray-code-using-recursion/

⇱ Binary to Gray code using recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary to Gray code using recursion

Last Updated : 28 Feb, 2026

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, two consecutive bits differ by exactly one bit. The most significant bit (MSB) of the Gray Code is always the same as the MSB of the binary number.

Examples: 

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

Input: 11
Output: 10
Explanation: The Gray Code for binary 11 is 10.

Approach [Using Recursion]

The idea is based on the property that each bit of the Gray Code can be obtained by performing XOR between the current binary bit and the previous binary bit.

To generate the Gray Code, the binary number is processed recursively from right to left. In each step, the last binary digit is compared with the second last digit. If both digits are different, 1 is appended to the Gray Code; otherwise, 0 is appended. The function is then recursively called on the remaining digits (n / 10).

The result of the recursive call is multiplied by 10 to shift the digits to the left, and the new Gray Code bit is added. The base case occurs when n == 0, where the function returns 0.


Output
1110011

Time Complexity: O(log10(n)), as the function processes one digit in each recursive call.
Auxiliary Space: O(log10(n)), due to recursive call stack for each digit.

Comment