Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading