在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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短