Bank app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-415strings
A bank app keeps very large totals, such as long-term ledger sums, as text, because they do not fit any integer type. A report adds two of them.
Each total is a string of digits with no sign and no leading zeros, except the number 0 itself. A total can have up to 1,000,000 digits, so the report must add them digit by digit, like on paper.
Write add_digit_strings(first, second).
first and second are non-negative whole numbers written in decimal digits. Neither has a leading zero, except that the number 0 is written 0.Input: first = "8765", second = "4378"
Output: "13143"8765 + 4378 = 13143.
Add from the last digit, with a carry, and append each digit to a builder.
| Digits from the right | Carry in | Total | Digit written | Carry out |
|---|---|---|---|---|
| 5 and 8 | 0 | 13 | 3 | 1 |
| 6 and 7 | 1 | 14 | 4 | 1 |
| 7 and 3 | 1 | 11 | 1 | 1 |
| 8 and 4 | 1 | 13 | 3 | 1 |
| none | 1 | 1 | 1 | 0 |
The digits written are 3, 4, 1, 3, 1. They are in reverse order, so reversing them once gives 13143.
Input: first = "0", second = "0"
Output: "0"The sum of zero and zero is zero, with one digit.
Input: first = "999999999999999999999", second = "1"
Output: "1000000000000000000000"A carry runs through all 21 digits and adds one digit at the front.
1 ≤ first.length ≤ 1,000,000 and 1 ≤ second.length ≤ 1,000,000 (digits)0 to 9, and have no leading zero except the number 0No integer type holds a number with a million digits, so you add digit by digit. Putting each new digit in front of the answer so far copies the answer at every step, which is about 5 × 10^11 characters for a million digits. Appending the digits and reversing once costs about n steps.