簡體   English   中英

Python 使用“小學”算法添加二進制數

[英]Python Adding Binary Numbers Using “Elementary School” Algorithm

我必須編寫一個代碼,它接受兩個輸入二進制數(作為字符串)並使用“小學”算法將它們相加。 這是代碼輸入和輸出的樣子:

>>>addBinary("11","1")
'100'

我曾嘗試自己編寫一些代碼,但我被卡住了:

def addBinary(s,t, b = 0):
    if '' == s or '' == t:
        return s + t
    if 1 == len(s) or 1 == len(s):    
        if 0 == b:
            if (0 == s[-1] and 1 == t[-1]) or (1 == s[-1]and 0 == t[-1]):
                return addBinary(s[:-1],t[:-1]) + '1'
            elif 0 == s[-1] and 0 == t[-1]:
                return addBinary(s[:-1],t[:-1]) + '0'
            else:
                return addBinary(s[:-1],t[:-1],1) + '0'
        else:
            if (0 == s[-1] and 1 == t[-1]) or (1 == s[-1]and 0 == t[-1]):
                return addBinary(s[:-1],t[:-1],1) + '0'
            elif 0 == s[-1] and 0 == t[-1]:
                return addBinary(s[:-1],t[:-1]) + '1'
            else:
                return addBinary(s[:-1],t[:-1],1) + '0'

當我下降到字符串中剩下的 1 個元素時,我遇到了麻煩。 我在創建基本案例時遇到問題

PS:我必須對這段代碼使用遞歸。 我不允許使用循環。

一些問題:

  • 只有當b = 0時才返回s + t ,否則返回的值將不正確。
  • 當其中一個字符串有一位數字時,不需要特殊情況。
  • 但是,有必要處理其中一個字符串為空並且您無法根據第一條規則以s + t退出s + t情況。
  • 可以避免多次重復幾乎相同的代碼

有幾種方法可以做到,但這里是一種:

def addBinary(s, t, carry = 0):
    if ('' == s or '' == t) and carry == 0:
        return s + t
    digit = carry
    carry = 0
    if s != '' and s[-1] == '1':
        carry = digit
        digit = 1 - digit
    if t != '' and t[-1] == '1': 
        carry += digit
        digit = 1 - digit
    return addBinary(s[:-1], t[:-1], carry) + str(digit)

請注意, digit = 1 - digit只是將 1 翻轉為 0 和將 0 翻轉為 1 的一種方式。

def add_binary(A:str,B:str)->str:
    result=[]
    carry=0
    i,j=len(A)-1,len(B)-1 # find the max index of strings
    while i>0 or j>0 or carry:
        total=carry # total is initially "carry" then we add values
        if i>=0:
            total+=int(A[i]) # convert the str to int, then add to "total"
            i-=1
        if j>=0:
            total+=int(B[j]) # same as above total operation
            j-=1
        result.append(str(total%2)) # if total=2, we write 0, if total=1, it is 1, if 0 it is 0
        carry=total//2 # if total=2 carry=1, otherwise carry=0
    # so far this is the first iteration
    return ''.join(reversed(result))

我們這樣做了reversed(result)因為“010101010”,我們從末尾開始求和,並將其推送到數組。 所以二進制數字的最后一個元素相加並作為數組的第一個元素推送。 這就是我們逆轉它的原因。

作為旁注,最后兩行應該是:

    else:
        return addBinary(s[:-1],t[:-1],1) + '1'

當長度為 1 時,您不應該做任何不同的事情。當其中一個長度為零時,您應該做一些不同的事情,並且在這種情況下您需要正確處理進位。 b1時, return s + t不正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM