使用 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
廣告