[英]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 時,您不應該做任何不同的事情。當其中一個長度為零時,您應該做一些不同的事情,並且在這種情況下您需要正確處理進位。 當b
為1
時, return s + t
不正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.