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 num1num2BigIntegerlong
Example 1
Output: "134"
Example 2
Output: "533"
Example 3
Output: "0"
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.
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
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
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)longLong.parseLong("99999999999999999999")NumberFormatException
Reading one digit
How does the character '7'char'0''9''0''7' - '0'
When to stop adding columns
How many columns are there? Two positions, inum1jnum2
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 StringBuilderreverse()
Java Solution
The method addStrings
- First, create an empty
namedStringBuilder for the digits. Setsb to the last position ofi andnum1 to the last position ofj , and setnum2 to 0.carry - Add one column per pass of a
loop, which runs as long aswhile ori still points at a digit orj is above 0. Each pass starts the column'scarry atsum .carry - If
is 0 or more, add the digiti tonum1.charAt(i) - '0' and movesum one place left. Do the same withi andj .num2 - Append
, the digit written, tosum % 10 , and setsb tocarry , which is 0 or 1.sum / 10 - After the loop, reverse
and return it as asb .String
The main
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:
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.parseLongintsum
Complexity
Let m and n be the lengths of num1num2
- 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
goes over those digits once more.reverse() - Space: O(max(m, n)), because
holds one digit per column, at most max(m, n) + 1 of them, whilesb ,i ,j andcarry stay foursum values whatever the input.int
Multiplying two such strings instead of adding them is