我的二进制减法程序似乎不适用于某个特定值

My binary subtraction program seems to not work for one specific value

所以我正在制作这个减法程序,但真的不知道为什么它对这两个值不起作用。但是对于其他每一个它都有效吗?

def binmin(x, y):
    lenx = len(x)
    leny = len(y)
    x1 = list(x)
    y1 = list(y)
    difference= 0
    one = 0
    result = ""
    for i in range(len(x)):
        difference = str((int(x1[lenx - 1 - i])) - int(y1[leny - 1 - i]))
        if difference == "-1":
            difference = 2 - int(y1[leny - 1 - i])
            one = 1
        
        elif difference == "-2":
            one = 1
            difference = 0

        else:
            one = 0

        y1[leny - i - 2] = int(y1[leny - i - 2]) + one

        result = str(difference) + str(result)

    return result

print(binmin("11110000","00010001"))

变化:

if difference == "-1":
    difference = 2 - int(y1[leny - 1 - i])
    one = 1

至:

if difference == "-1":
    difference = 1
    one = 1

difference 最初为 "-1" 时,您需要借用,因此您实际上是在差值中添加 2。由于差异最初是 -1,因此您需要 2-1 = 1 作为新的差异。

最初的调整仅在 int(y1[leny - 1 - i])1 时有效,如果之前通过较早的借用进行了调整,则可能无效,在这种情况下可能 2 .