Binary Subtraction - Python

后端 未结 2 989
时光说笑
时光说笑 2021-01-12 08:37

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I\'ve found on this website).

2条回答
  •  醉梦人生
    2021-01-12 09:18

    Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.

    Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:

    if s == -1:  # 0-1
        if carry == 0:
            ...
        else:
            ...
    elif s == 0:  # 1-1 or 0-0
        if carry == 0:
            ...
        else:
            ...
    else:  # 1-0
        if carry == 0:
             ...
        else:
            ...
    

    This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.

提交回复
热议问题