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.

The problem can be formally stated as…

**Input:** Two \(n\) bit binary integers stored in two \(n\) element array of binary digits (either 0 or 1) \(A = \langle a_1, a_2, ... , a_n \rangle\) and \(B = \langle b_1, b_2, ... , b_n \rangle\).

**Output:** A \((n + 1)\) bit binary integer stored in \((n + 1)\) element array of binary digits (either 0 or 1) \(C = \langle c_1, c_2, ... , c_{n+1} \rangle\) such that \(C = A + B\).

We also assume the binary digits are stored with least significant bit first, i.e. from right to left, first bit in index \(1\), second bit in index \(2\), and so on. Why we are doing this is discussed after the pseudocode.

#### Left to Right or Right to Left

An earlier version of the solution presented here assumed the least significant bit was stored in index \(n\) instead of index \(1\). Which made the solution not only wrong (it did not handle all possible cases properly), it also caused a great deal of confusion in the comments section.

Here is why assuming least significant bit in index \(n\) will make the problem unnecessarily complicated.

Consider the following two binary additions

The one on the left adds \(111_b\) and \(1_b\) to \(1000_b\). In this case, \(n = 3\) and we end up with final array \(C\) of length \(n + 1 = 4\). The array indices are shown in blue with the assumption of storing bits as we they appear visually from left to right, i.e. most significant bit in first index and least significant bit in last index, \(n\).

In this particular case there is no complication, and we could have just designed our pseudocode to iterate from the opposite direction, from \(n\) **downto** \(1\), and stored the result of the addition in line 4 in \(C[i + 1]\) and the final \(carry\) in line 6 in \(C[1]\).

However, note that for the addition on the right, \(110_b\) and \(1_b\) sums up to \(111_b\), and we end up with final array \(C\) of length \(n = 3\). In this case, \(C[1]\) is empty (highlighted with light red), and we are left with the additional task of shifting all the elements to the left to meet our initial assumption of having most significant bit at index \(1\).

One can argue that having *zero* in the first index is not a deal breaker, but depending on the use case it might add up to redundant work. For example, let’s say we need to repeatedly do this addition. And every time we end up with a case like the right one. Then we would keep on adding redundant *zeroes* in the beginning of the resulting array.