Binary Subtraction - Python

后端 未结 2 990
时光说笑
时光说笑 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:01

    I hope the answer below it helps.

    def binarySubstration(str1,str2):
    if len(str1) == 0:
        return
    if len(str2) == 0:
        return 
    
    str1,str2 = normaliseString(str1,str2)
    startIdx = 0
    endIdx = len(str1) - 1
    carry = [0] * len(str1)
    result = ''
    
    
    while endIdx >= startIdx:
        x = int(str1[endIdx])
        y = int(str2[endIdx])
        sub = (carry[endIdx] + x) - y
    
        if sub == -1:
            result += '1'
            carry[endIdx-1] = -1
    
        elif sub == 1:
            result += '1'
        elif sub == 0:
            result += '0'
        else:
            raise Exception('Error')
    
        endIdx -= 1
       
    return result[::-1]
    

    normalising the strings

    def normaliseString(str1,str2):
        diff = abs((len(str1) - len(str2)))
        if diff != 0:
            if len(str1) < len(str2):
                str1 = ('0' * diff) + str1
                
            else:
                str2 = ('0' * diff) + str2
               
        return [str1,str2]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题