Add Strings

Add two whole numbers that arrive as strings of digits, the same way you add on paper, and return the sum as a string.

Given two non-negative whole numbers num1 and num2, each written as a string of digits, return their sum, also as a string. Do not turn the whole strings into numbers, and do not use BigInteger, the Java class for whole numbers of any length. The inputs can be far longer than a long can hold.

Example 1
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3
Input: num1 = "0", num2 = "0"
Output: "0"
Solution

The Idea

You learned this in school. To add 456 and 77 on paper, you write 77 under 456 with the last digits lined up, then add one column at a time, starting on the right. Here the numbers arrive as text, so each digit is a character in a string, and a string may hold hundreds of digits.

The picture below adds Example 2 that way, with the ones column on the right.

Adding 456 and 77 column by column from the right. Ones: 6 + 7 = 13, write 3, carry 1. Tens: 5 + 7 + 1 = 13, write 3, carry 1. Hundreds: 4 + 0 + 1 = 5, write 5. A StringBuilder holds 3, then 33, then 335, and reverse() gives 533.

Start in the ones column: 6 + 7 = 13. A column has room for one digit, so 3 goes into the row labelled "digit written", and the 1 moves on to the tens column. That 1 is the carry, the orange box in the row labelled "carry out". In the tens column it shows up again as "carry in", so the sum is 5 + 7 + 1 = 13: another 3 written, another 1 carried. In the hundreds column, "77" has no digit left, so the grey box counts as 0, and 4 + 0 + 1 = 5.

Why not simply turn both strings into numbers and add them? A long stops at 9,223,372,036,854,775,807, a number of only 19 digits, while these strings can hold hundreds. So what does one column need to know about the rest of the numbers?

It needs to know only the carry. A column adds two digits and a carry, so its sum is at most 9 + 9 + 1 = 19. The digit written is the last digit of that sum, and the carry out is 0 or 1. However long the strings are, every value in the work stays below 20.

One detail comes from the order. The digits come out right to left, ones first. The right side of the picture shows them collected in a StringBuilder, a string that can grow: it holds 3, then 33, then 335. Reversing it once at the end gives "533".

Solution Approach

Four things need settling: why converting the whole strings fails, how to read one digit, when to stop adding columns, and how to put the digits in the right order.

Converting the whole strings

What goes wrong with Long.parseLong(num1) + Long.parseLong(num2)? It works while both numbers fit in a long. A string of 20 nines does not fit: Long.parseLong("99999999999999999999") throws a NumberFormatException. Adding column by column never builds the whole number, so the length of the strings does not matter.

Reading one digit

How does the character '7' become the number 7? In Java a char is stored as a number code, and the digits '0' to '9' have codes that follow each other, 48 to 57. Subtracting the code of '0' leaves the digit's value: '7' - '0' is 55 - 48, which is 7.

When to stop adding columns

How many columns are there? Two positions, i in num1 and j in num2, start at the last character of each string and move left by one after each column. When one string runs out first, its position drops below 0 and that number adds nothing, just like the grey 0 in the picture.

The loop must also keep going while a carry is left. Adding "999" and "1" fills three columns with 0 and still holds a carry of 1, which needs a fourth column of its own. A version that stops when both strings run out returns "000" for that input.

Putting the digits in order

Where does each new digit go? Appending it to the end of the StringBuilder keeps the work simple, and the builder then holds the answer backwards. One call to reverse() at the end turns "335" into "533".

Java Solution

The method addStrings works in these steps:

  1. First, create an empty StringBuilder named sb for the digits. Set i to the last position of num1 and j to the last position of num2, and set carry to 0.
  2. Add one column per pass of a while loop, which runs as long as i or j still points at a digit or carry is above 0. Each pass starts the column's sum at carry.
  3. If i is 0 or more, add the digit num1.charAt(i) - '0' to sum and move i one place left. Do the same with j and num2.
  4. Append sum % 10, the digit written, to sb, and set carry to sum / 10, which is 0 or 1.
  5. After the loop, reverse sb and return it as a String.

The main method runs the three examples, "999" plus "1", where the carry outlasts both numbers, and a 20-digit number of nines added to "1" and to itself.

Java
public class AddStrings {

    public static String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0) {
                sum += num1.charAt(i--) - '0';    // a finished number counts as 0
            }
            if (j >= 0) {
                sum += num2.charAt(j--) - '0';
            }
            sb.append(sum % 10);                  // the digit written in this column
            carry = sum / 10;                     // 0 or 1, carried to the next column
        }
        return sb.reverse().toString();           // digits were produced from right to left
    }

    public static void main(String[] args) {
        System.out.println(addStrings("11", "123"));
        System.out.println(addStrings("456", "77"));
        System.out.println(addStrings("0", "0"));
        System.out.println(addStrings("999", "1"));
        String big = "99999999999999999999";      // 20 nines, too long for a long
        System.out.println(addStrings(big, "1"));
        System.out.println(addStrings(big, big));
    }
}

Running it prints:

Output
134
533
0
1000
100000000000000000000
199999999999999999998

The line 533 is Example 2, the sum worked out in the picture. Below it, "0" plus "0" prints 0 and not an empty line, because the loop still runs once for the single column and writes its 0.

Look at 1000: it has one digit more than "999". After three columns the carry of 1 is still there, so the loop makes a fourth pass just to write it.

The last two lines start from 20 nines, a number that Long.parseLong rejects. Adding 1 gives a 1 followed by 20 zeros. Adding the number to itself gives 199999999999999999998, where every column summed to 9 + 9 + 1 = 19 at most, so the int named sum never comes near its limit.

Complexity

Let m and n be the lengths of num1 and num2; the work is one pass per column plus the final reverse.

  • Time: O(max(m, n)), because each pass of the loop handles one column, the longer string's digits plus at most one final carry make at most max(m, n) + 1 columns, and reverse() goes over those digits once more.
  • Space: O(max(m, n)), because sb holds one digit per column, at most max(m, n) + 1 of them, while i, j, carry and sum stay four int values whatever the input.

Multiplying two such strings instead of adding them is Multiply Strings.