在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 婆婆高寿祝福语大全简短