Should addition of binary numbers in array be done from left-to-right or right-to-left?

So i was solving exercise 2.1-5 from CLRS book where in we need to add two n-bit binary integers a and b, stored in n-element array. I found the following solution:

def AddBinary(A,B):
    n = max(len(A), len(B))
    C = [0 for i in range(n+1)]
    carry = 0

    for i in range(n):
        C[i] = (A[i] + B[i] + carry) % 2
        carry = (A[i] + B[i] + carry) // 2

    C[n] = carry

    return C


A = [0,1,1,1,0,0,1]
B = [0,1,1,0,1,1,1]

C = AddBinary(A,B)
print(C)

But here the addition happens from left-to-right unlike the regular right-to-left addition. Is this solution correct? or should i change it to add from right-to-left.

>Solution :

The solution you provided adds the binary numbers from left to right, which is correct. In binary arithmetic, adding from left to right is equivalent to adding from right to left. It doesn’t matter which direction you choose as long as the carry is correctly propagated.

The code correctly computes the sum of each digit and the carry, so it should give the correct result.

Leave a Reply