342/670

342. Add Strings

Easy

You receive two non-negative integers num1 and num2 — but as strings of digits, and they may be far too long to fit in any built-in integer type. Compute their sum and return it, also as a string of digits.

Do it the way you learned in school: column by column from the rightmost digits, carrying into the next column when a column overflows 9. Converting the full strings with a big-integer type or a parse-to-int call defeats the exercise.

The returned string must have no leading zeros, except that a sum of zero is exactly "0".

Example 1 — schoolbook column addition456 + 77 column by column from the right: 6+7 = 13 writes 3 and carries 1, 5+7+1 = 13 writes 3 and carries 1, 4+1 = 5. The digits come out right-to-left: 533.
11carries456+77533work right → left, then the answer reads 533

Example 1:

Input: num1 = "456", num2 = "77"

Output: "533"

Explanation: Rightmost column 6 + 7 = 13: write 3, carry 1. Next 5 + 7 + 1 = 13: write 3, carry 1. Last 4 + 1 = 5. Reading the written digits gives 533.

Example 2:

Input: num1 = "11", num2 = "123"

Output: "134"

Explanation: No column exceeds 9 here, so no carrying happens: 11 + 123 = 134.

Example 3:

Input: num1 = "0", num2 = "0"

Output: "0"

Explanation: Zero plus zero is zero, written as the single digit "0".

Constraints:

  • 1 ≤ num1.length, num2.length ≤ 10⁴
  • num1 and num2 contain only the digits 0-9
  • Neither input has leading zeros, except the number 0 itself

Hints:

Walk both strings from their last characters with two indices, adding digit + digit + carry each step. A character digit becomes a number via ord(c) − ord('0') (or c − '0').

When the pointers run past the left end, treat the missing digit as 0 — and after the loop, don't forget a leftover carry: 999 + 1 must still emit that final 1. You build the answer right-to-left, so reverse it once at the end.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: num1 = "456", num2 = "77"

Expected output: "533"