You get two non-negative whole numbers, num1 and num2, written as strings of digits. Return their sum, also as a string of digits.
The numbers can be thousands of digits long, far past what any built-in integer type holds. So you may not turn the strings into numbers, and you may not use a big-integer library. Add them the way you would on paper.
Example 1
Input: num1 = "958", num2 = "67" Output: "1025" Why: 958 + 67 = 1025; the carry makes a new leading digit
2 more examples and the constraints
Example 2
Input: num1 = "999", num2 = "1" Output: "1000" Why: the carry ripples through every column
Example 3
Input: num1 = "0", num2 = "0" Output: "0" Why: zero plus zero is still a single 0
Constraints
- 1 ≤ length of num1, length of num2 ≤ 10,000
- Both strings hold only the digits 0 to 9
- No leading zeros, except for the number 0 itself
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Pad and prependO(n²)
- Two pointers and a carryO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 10,000-digit numbers | Verdict |
|---|---|---|---|
| Pad and prepend | O(n²) | Correct; hides a quadratic copy | |
| Two pointers and a carry | O(n) | Best; one pass and one reverse |
m, n = lengths of the two strings; n alone means the longer one.
Edge cases to test
- Carry past the front. "999" + "1" needs a new leading digit: "1000".
- Different lengths. "1" + "99999999999999999999" keeps going after the short number runs out.
- Zeros. "0" + "0" is "0", and "0" + "4180" is "4180", with no extra zeros.
- Too big for 64 bits. Two 20-digit numbers already overflow a long, so any shortcut through an integer type fails.
Common mistakes
- Stopping when both pointers run out and dropping the last carry.
- Converting the whole string with
int()orparseInt, which the problem forbids and which overflows in Java and C++. - Forgetting to reverse the digits, or reversing the inputs and the output twice.
How to talk through it
- 1Clarify. Can the inputs be empty or negative? Can I convert single characters to digits?
- 2Describe paper addition. Right to left, one column at a time, carrying 1 when a column reaches 10.
- 3Point out the prepend cost. Building the string from the front is quadratic; append and reverse instead.
- 4Code the loop. Loop while either pointer or the carry is left, and treat a finished pointer as 0.
- 5Test out loud. Run "999" + "1", "0" + "0" and two numbers of different lengths.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?