Home > Backend Development > C++ > Translate the following into Chinese: Convert binary to gray code in C program using recursion

Translate the following into Chinese: Convert binary to gray code in C program using recursion

PHPz
Release: 2023-09-12 17:53:02
forward
710 people have browsed it

Translate the following into Chinese: Convert binary to gray code in C program using recursion

Binary numbers are numbers with only two digits, 0 and 1.

Gray code is a special type of binary number whose property is that two consecutive digits of the code em> cannot differ by more than one digit. This property of Gray code makes it more useful in K-map, error correction, communication, etc.

This makes binary to Gray code conversion necessary. So, let us look at the algorithm to convert binary to Gray code Use recursion.

Example

Let us take Gray code code as an example

Input : 1001
Output : 1101
Copy after login

Algorithm

Step 1 : Do with input n :
   Step 1.1 : if n = 0, gray = 0 ;
   Step 1.2 : if the last two bits are opposite,
      gray = 1 + 10*(go to step 1 passing n/10).
   Step 1.3 : if the last two bits are same,
      gray = 10*(go to step 1 passing n/10).
Step 2 : Print gray.
Step 3 : EXIT.
Copy after login

Example

#include <iostream>
using namespace std;
int binaryGrayConversion(int n) {
   if (!n)
      return 0;
   int a = n % 10;
   int b = (n / 10) % 10;
   if ((a && !b) || (!a && b))
      return (1 + 10 * binaryGrayConversion(n / 10));
   return (10 * binaryGrayConversion(n / 10));
}
int main() {
   int binary_number = 100110001;
   cout<<"The binary number is "<<binary_number<<endl;
   cout<<"The gray code conversion is "<<binaryGrayConversion(binary_number);
   return 0;
}
Copy after login

Output

The binary number is 100110001
The gray code conversion is 110101001
Copy after login

The above is the detailed content of Translate the following into Chinese: Convert binary to gray code in C program using recursion. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template