如何在Python中使用遞迴將十進位制轉換為二進位制?
在本文中,我們將向您展示如何在Python中使用遞迴將十進位制轉換為二進位制。
十進位制數是大眾最熟悉的數字系統。它是基數為10的系統,只有10個符號——0、1、2、3、4、5、6、7、8和9。而二進位制數是數字系統、網路和計算機專業人員最熟悉的數字系統。它是基數為2的系統,只有2個符號:0和1,這些數字分別可以用關和開表示。
當我們將數字從十進位制系統轉換為二進位制系統時,我們使用的是十進位制到二進位制的轉換。數字系統中使用的數字總數決定了所有數字系統的基數。例如,二進位制系統基數為二,因為它只使用兩位數字來表示一個數字。同樣,十進位制系統基數為十,因為一個數字由十位數字表示。
使用遞迴(第一種方法)
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個遞迴函式 `getBinaryForm()`(使用 `def` 關鍵字)來將作為引數傳遞給它的十進位制數轉換為二進位制形式。
使用 `if` 條件語句檢查傳遞的數字是否使用 `==` 運算子等於 0。
如果條件為真,即傳遞的十進位制數為 0,則返回 0。
否則,使用遞迴邏輯返回傳遞給函式的十進位制數的二進位制形式(使用模運算子 (%) 獲取數字的最後一位,將數字除以 2(一半),乘以 10,並使用此值再次呼叫遞迴函式)。
建立一個變數來儲存輸入數字。
透過將輸入十進位制數作為引數傳遞來呼叫 `getBinaryForm()` 函式,並列印函式返回的十進位制數的二進位制等效值。
示例
以下程式使用遞迴返回十進位制數的二進位制形式:
# creating a function to convert decimal number passed to it # as an argument into a binary form def getBinaryForm(decimalnum): # checking whether the number passed is equal to 0 if decimalnum == 0: # returning 0 if the number passed is 0 return 0 else: # Else getting the last bit of the number and dividing the number by 2(half) and multiplying it with 10 # Calling the recursive function again with this value-added return (decimalnum % 2 + 10 * getBinaryForm(int(decimalnum // 2))) # input decimal number decimalnum = 5 print("The binary equivalent of",decimalnum,"is:") # calling the getBinaryForm() function by passing the decimal number as an argument print(getBinaryForm(decimalnum))
輸出
執行上述程式將生成以下輸出:
The binary equivalent of 5 is: 101
使用遞迴(第二種方法)
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個遞迴函式 `getBinaryForm()`(使用 `def` 關鍵字)來將作為引數傳遞給它的十進位制數轉換為二進位制形式。
使用 `if` 條件語句檢查傳遞的數字是否使用 `==` 運算子等於 0。
如果條件為真,即傳遞的十進位制數為 0,則返回 0。
透過傳遞給定數字的一半來再次遞迴呼叫該函式,並將此結果儲存在一個變數中。
使用模運算子 (%) 獲取給定十進位制數的最後一位,並將其新增到上述結果中(乘以10)。
建立一個變數來儲存輸入數字。
透過將輸入十進位制數作為引數傳遞來呼叫 `getBinaryForm()` 函式,並列印函式返回的十進位制數的二進位制等效值。
示例
以下程式使用遞迴返回十進位制數的二進位制形式:
# creating a function to convert decimal number passed to it # as an argument into a binary form def getBinaryForm(decimalnum): # checking whether the number passed is equal to 0 if decimalnum == 0: # returning 0 if the number passed is 0 return 0 # Call the function recursively again by passing the given number by half result = getBinaryForm(decimalnum // 2) # Getting the last bit and multiply the result with 10 return decimalnum % 2 + 10 * result # input decimal number decimalnum = 500 print("The binary equivalent of",decimalnum,"is:") # calling the getBinaryForm() function by passing # the decimal number as an argument print(getBinaryForm(decimalnum))
輸出
執行上述程式將生成以下輸出:
The binary equivalent of 500 is: 111110100
結論
在本文中,我們學習了兩種使用遞迴計算給定十進位制數的二進位制格式的不同方法。我們學習瞭如何透過傳遞某個值(結果)來呼叫遞迴函式。我們還學習瞭如何將數字除以二以僅獲得整數。