首頁  >  文章  >  後端開發  >  將以下內容翻譯為中文:使用遞歸在C程式中將二進位轉換為格雷碼

將以下內容翻譯為中文:使用遞歸在C程式中將二進位轉換為格雷碼

PHPz
PHPz轉載
2023-09-12 17:53:02642瀏覽

將以下內容翻譯為中文:使用遞歸在C程式中將二進位轉換為格雷碼

二進位數是只有兩位 0 和 1 的數字。

格雷碼是一種特殊類型的二進制數,其屬性是程式碼的兩個連續數字 em> 的差異不能超過一位。格雷碼的這項特性使其在 K-map、糾錯、通信等方面更加有用。

這使得二進位到格雷碼的轉換成為必要。那麼,讓我們來看看將二進位轉換為格雷碼的演算法 使用遞迴

範例

讓我們以格雷碼程式碼為例

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

以上是將以下內容翻譯為中文:使用遞歸在C程式中將二進位轉換為格雷碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除