使用 C 语言中递归将二进制转换为格雷码
二进制数是仅包含两个位 0 和 1 的数字。
格雷码是一种特殊的二进制数类型,具有一个特性,即该代码的两个连续数字差异不会超过一位。格雷码的这一特性使其在 K-maps、纠错、通信等方面更加有用。
因此,需要将二进制转换为格雷码。因此,让我们来看一下使用递归将二进制转换为格雷码的算法。
示例
让我们举一个格雷码的例子
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP