Binary to Gray Code Using Recursion in Java2 May 2025 | 3 min read Named for Frank Grey, Grey Code is a binary numeral system in which there is just a single bit difference between two successive values. It is also known as the "Reflected Binary Code" because the (n-1)-bit form of it may be reflected and appended to itself to create the n-bit version. Importance and Uses of Gray CodeGray Code is mainly used in digital communications and error correction because it reduces the chance of errors when a single-bit change occurs. It is especially critical in scenarios like mechanical encoders or analog-to-digital converters, where noise or inaccuracies could lead to erroneous bit representations. In practical use cases, the reflected Gray Code ensures smooth transitions between values, making it robust for mechanical and electrical signal interpretation. Recursive Approach to Convert Binary to Gray CodeThe recursive approach leverages the following formula to convert binary to Gray Code: Here, the right-shift operation (>>) shifts all bits of the binary number to the right by one position, essentially halving the number. XOR (^) then compares the original binary number with the right-shifted version bit by bit. This approach guarantees that only one bit changes at a time, thus ensuring the sequence is a Gray Code. File Name: BinaryToGray.java Output: Sample Output 1: Enter a number: 5 Binary representation of 5: 101 Gray Code of 5: 111 Sample Output 2: Enter a number: 7 Binary representation of 7: 111 Gray Code of 7: 100 ExplanationThe Java code consists of a class BinaryToGray that houses three main functions and a main method. The recursive function binaryToGray() performs the actual conversion from binary to Gray Code using the XOR (^) operation with the right-shifted version of the input number. The base case checks if the number is zero and returns zero since zero in binary is the same in Gray Code. The function toBinary() converts a number to its binary representation using Java's built-in Integer.toBinaryString(). Similarly, toGrayCodeString() calls the binaryToGray() function and returns the Gray Code's binary representation. In the main() method, the program prompts the user to enter an integer, which is then passed to the conversion functions to print both the binary and Gray Code forms. The use of recursion in binaryToGray() highlights that, even if the conversion formula looks simple, the recursive structure manages to trace the problem back to its base case efficiently. Complexity AnalysisTime Complexity: The given code has a time complexity of O(1) since the XOR and right-shift operations execute in constant time. There is no iteration proportional to the size of the input, making the program efficient. Space Complexity: The space complexity is also O(1) as the program uses only a few integer variables, independent of the input size. ConclusionConverting binary numbers to Gray Code using a recursive approach leverages the simplicity of the XOR and right-shift operations. This method is efficient and intuitive, reducing the chance of errors in applications that require sequential binary transitions. The recursive nature is conceptually elegant, making it easy to visualize how the base case and recursive step work together to achieve the desired conversion. The Java implementation provided here ensures both accuracy and a straightforward pathway to understanding the process, making it an ideal technique for various digital applications. Next TopicIs Java Interpreted or Compiled? |
Each and every programming language, including Java, is bounded with null. There is no programmer who didn't face any issue in the code related to null. Programmers mainly face NullPointerException when they try to perform some operations with null data. NullPointerException is a class available that...
5 min read
It is that part of Computer Science that deals with image manipulation and analysis in the digital domain. Image processing, due to the increasing use of multimedia, has become an integral part of tasks like image enhancement, text extraction, artistic effects, etc. In this section, we...
9 min read
What is Authentication? Authentication is the process of verifying the credentials a user provides with those stored in a system to prove the user is who they say they are. If the credentials match, then we grant access. If not, we deny it. Methods of Authentication Single Factor authentication: This...
6 min read
In Java, the Singleton pattern and static classes are employed to control instance creation and access to class-level behavior, but they serve distinct purposes and possess different characteristics. Singleton Pattern The Singleton pattern in Java is a design pattern that guarantees the existence of only one instance...
6 min read
In this section, we will learn how to interchange diagonals of a matrix through a Java program. It is usually asked in Java interviews and academics. Consider the above 4*4 matrix whose size is n. In the above matrix, we have to swap the following indexes to interchange...
4 min read
In this section, we will discuss the how to reverse a string using a byte array in Java. The following are the steps to reverse a string in Java using a byte array. The first step in this method is to generate a temporary byte[] with a length...
4 min read
The problem's primary goal is to determine the number of positive integers up to a specific number, n, that contains all distinct digits, meaning that no digit appears more than once in the number. In contrast to 11345, which is not a unique number due to...
16 min read
The number of GP sequence problems in Java involves determining the count of valid geometric progression sequences within a given set of numbers. Geometric progressions, defined by a common ratio, are essential in various fields. In this tutorial, we will find the count of GP sequence...
10 min read
Introduction Backtracking is an algorithmic technique that utilizes a brute-force approach to find the desired solution. Put simply, it exhaustively tries all possible solutions and selects the optimal one. The term backtracking refers to the process of retracing one's steps and exploring other alternatives if the current...
7 min read
In this section, we will discuss what is Mersenne number and also create Java programs to check if the given number is a Mersenne number or not. The Mersenne number program frequently asked in Java coding interviews and academics. Mersenne Number In mathematics, a Mersenne number is a...
3 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India