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. State the problem formally and write pseudocode for adding the two integers.
Solution:
- C ← [1 ... n + 1] ▹ C is zero-filled.
- for i ← 1 to n
- do sum ← A[i] + B[i] + C[i]
- C[i] ← sum % 2
- C[i + 1] ← sum / 2 ▹ Integer division.
- output C
Question:
- I thought the C[i] is A[i]+B[i] why are you adding sum ← A[i] + B[i] + C[i] in step 3?
- why sum % 2 (why need to use modulo in step 4?)
- why sum / 2 (why need to use division in step 5?)
Could you please explain above solution with real example? Thanks.