Binary Subtraction - Python

后端 未结 2 1009
时光说笑
时光说笑 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]
    

提交回复
热议问题