【问题标题】:Can't figure out what is wrong with my binary addition algorithm无法弄清楚我的二进制加法算法有什么问题
【发布时间】: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

【问题讨论】:

    标签: python algorithm binary


    【解决方案1】:

    您的计算方向错误。您的代码从最重要的位置值开始,然后向后工作。

    即你的例子实际上是在做 10101101 + 10001001。

    将您的 for 循环更改为:for i in range(len(x) - 1, -1, -1): 或使用 x = x[::-1]y = y[::-1] 反转您的输入。

    最后一个 if 语句也应该是 if carry:,因为它要么是真要么是假,而不是 1 或 0。

    【讨论】:

    • 哇!这很明显,谢谢你这工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多