在C程序中使用递归的二进制到格雷代码

二进制数是只有两位0和1的数字。

格雷码是一种特殊类型的二进制数,其性质是该代码的两个连续数不能超过一个位。格雷码的此属性使其可用于更多的K映射,纠错,通信等。

这使得必须将二进制代码转换为格雷代码。因此,让我们看一下一种使用递归二进制代码转换为格雷码的算法。

示例

让我们以格雷码的示例为例

Input : 1001
Output : 1101

算法

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.

示例

#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;
}

输出结果

The binary number is 100110001
The gray code conversion is 110101001