在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
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短