【发布时间】:2021-05-18 22:57:05
【问题描述】:
我正在 python 中创建一个二进制加法算法。从我得到的输出中,似乎二进制字符串正在反转并以这种方式添加。我似乎无法弄清楚是什么原因造成的。
def addBinary(x, y):
carry = False
result = ''
for i in range(len(x)):
if carry == True:
if x[i] == '1' and y[i] == '1':
result = '1' + result
if x[i] =='1' and y[i] == '0':
result = '0' + result
if x[i] =='0' and y[i] == '1':
result = '0' + result
if x[i] == '0' and y[i] == '0':
result = '1' + result
carry = False
else:
if x[i] == '1' and y[i] == '1':
result = '0' + result
carry = True
if x[i] =='1' and y[i] == '0':
result = '1' + result
if x[i] =='0' and y[i] == '1':
result = '1' + result
if x[i] == '0' and y[i] == '0':
result = '0' + result
print(result)
if carry == True:
result = '1' + result
else:
result = '0' + result
return result
print(addBinary('10110101','10010001'))
输出是
0
10
110
0110
10110
110110
0110110
00110110
000110110
正确的输出是 0101000110
【问题讨论】: