Add Numbers Written as Text
EasyMath & Geometry
Problem
An accounting export stores amounts as decimal strings that can be thousands of digits long, too long for any built-in integer type.
Given two non-negative integers first and second as strings, return their sum as a string. Do not convert the whole strings to numbers.
Example 1
- Input:
- first = "456", second = "77"
- Output:
- "533"
6 + 7 = 13 (write 3, carry 1), 5 + 7 + 1 = 13 (write 3, carry 1), 4 + 1 = 5.
Example 2
- Input:
- first = "999", second = "1"
- Output:
- "1000"
The carry ripples all the way and adds a new leading digit.
Example 3
- Input:
- first = "0", second = "0"
- Output:
- "0"
Constraints
- 1 ≤ first.length, second.length ≤ 10^4
- Both contain digits only and have no leading zeros, except the number "0" itself
Hint
Show the first hint
Do it the way you add on paper: from the rightmost digit to the left.
Walkthrough
How to approach it
01Clarify before coding
- Can the inputs have different lengths? Yes; treat the missing digits of the shorter one as 0.
- Are there signs or decimal points? No, only non-negative integers.
- Can I just use a big-integer library? No: the point is the digit-by-digit algorithm.
02Brute force
Convert both strings to numbers and add them.
Cost: Fails outright: 10^4 digits overflow every fixed-width type. Prepending each digit to a string instead of reversing once also makes it O(n²).
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.