我正在用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
你的数学方向不对。您的代码从值的最重要位置开始,并向后运行
你的例子实际上是10101101+10001001
将for循环更改为:
for i in range(len(x) - 1, -1, -1):
,或使用x = x[::-1]
和y = y[::-1]
反转输入另外,您的最后一个if语句应该是
if carry:
,因为它要么是真的,要么是假的,而不是1或0相关问题 更多 >
编程相关推荐