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