pythonalgorithmbinary

Binary addition algorithm is providing incorrect results


I'm creating a binary addition algorithm in python. from the output I'm getting it seems as though the binary strings are getting inverted and added that way. I can't seem to figure out what's causing this.

def addBinary(x, y):
    carry = False
    result = ''   
    for i in range(len(x)):
        if carry == True:
            if x[i] == '1' and y[i] == '1':
                result = '1' + result
            if x[i] =='1' and y[i] == '0':
                result = '0' + result
            if x[i] =='0' and y[i] == '1':
                result = '0' + result
            if x[i] == '0' and y[i] == '0':
                result = '1' + result
                carry = False
        else:
            if x[i] == '1' and y[i] == '1':
                result = '0' + result
                carry = True
            if x[i] =='1' and y[i] == '0':
                result = '1' + result
            if x[i] =='0' and y[i] == '1':
                result = '1' + result
            if x[i] == '0' and y[i] == '0':
                result = '0' + result
        print(result)
    if carry == True:
        result = '1' + result
    else:
        result = '0' + result
    return result
print(addBinary('10110101','10010001'))

and the output is

0
10
110
0110
10110
110110
0110110
00110110
000110110

the correct output is 0101000110


Solution

  • You're doing your math in the wrong direction. Your code starts at the most significant place value, and works backwards.

    Ie Your example is actually doing 10101101 + 10001001.

    Change your for loop to: for i in range(len(x) - 1, -1, -1): OR reverse your inputs with x = x[::-1] and y = y[::-1].

    Also your last if statement should be if carry: since it's either true or false, not 1 or 0.