Python Can';我不知道我的二进制加法算法出了什么问题

Python Can';我不知道我的二进制加法算法出了什么问题,python,algorithm,binary,Python,Algorithm,Binary,我正在用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 =

我正在用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循环更改为:
范围内的i(len(x)-1,-1,-1):
或使用
x=x[:-1]
y=y[:-1]
反转输入


最后一个if语句应该是
if-carry:
,因为它不是1就是0,而是真是假。

wow!这很明显,谢谢你,这很有效。