Binary Subtraction - Python
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.