Why is a carry need in CLRS problem 2.1-4 adding two binary array?

169 Views Asked by At

CLRS is the book Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein.

Problem:

Consider the problem of adding two n-bit binary integers, stored in two n element arrays A and B. The sum of the two integers should be stored in binary form in an (n + 1) element array C.

Why is carry needed in the correct solution?

My solution:

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

correct solution:

def AddBinary(A,B):
    carry = 0 
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    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
1

There are 1 best solutions below

1
CryptoFool On

You're asking about the basic nature of performing addition place by place in whatever base. If you can recall how we were taught decimal (base 10) addition early on, we were told to carry the "overflow" to the next digit, right? The code needs to do the same thing. The carry is a critical part of the operation.

Here's a simple way to see this. Consider adding two 2-digit binary numbers:

01 + 01 = 10   # (1 + 1) % 2 == 0 + carry, (0 + 0 + carry) % 2 == 1

or in decimal, 1 + 1 = 2. Now apply your logic that ignores the carry:

01 + 01 = 00   # (1 + 1) % 2 == 0, (0 + 0) % 2 == 0

so here, 1 + 1 = 0. That clearly isn't correct. In this trivial example, the carry produces the entirety of the resulting value.