Search code examples
pythonbinarysubtraction

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


So I'm making this subtraction program and really don't know why it does not work for these two values. For every other one it works though?

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"))

Solution

  • Change:

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

    to:

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

    When difference is initially "-1", you need to borrow, so you're effectively adding 2 to the difference. Since the difference was originally -1, you want 2-1 = 1 for the new difference.

    The original adjustment only worked if int(y1[leny - 1 - i]) was 1, which it might not be if it had previously been adjusted by an earlier borrow, in which case it could be 2.