Add Strings
Easy
Topics
Given two non-negative integers num1 and num2 represented as strings, return their sum as a string. You must not convert the inputs to integers directly or use a big-integer library.
Example 1
Input: num1 = "11", num2 = "123" Output: "134"
Example 2
Input: num1 = "456", num2 = "77" Output: "533"
Example 3
Input: num1 = "0", num2 = "0" Output: "0"
Constraints
- 1 <= num1.length, num2.length <= 10^4
- num1 and num2 consist of only digits.
- num1 and num2 do not contain any leading zero except the number 0 itself.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The problem forbids converting the strings to integers, which is the whole point: it asks you to implement addition rather than call it. In a language with arbitrary-precision integers the ban feels artificial, but these inputs reach 10^4 digits, far beyond any fixed-width type — so for most languages this is the only way, not an artificial restriction.
Addition works right to left because that is the direction carry travels. At each position, add the two digits plus whatever carried in, write down the units digit, and carry the tens. The only wrinkle is that the strings can be different lengths, and the carry can outlive both of them — 999 + 1 produces a fourth digit from nothing.
The loop condition handles all three endings at once: keep going while either string has digits left or a carry is still pending. That single condition removes the padding, the length comparison, and the post-loop carry flush that hand-rolled versions usually need.
Approach
- Two indices at the ends of the strings, carry at 0, and a list for the output digits.
- While
i >= 0 or j >= 0 or carry: start from the carry, add each available digit, appendd % 10, setcarry = d // 10. - Digits were produced least-significant first, so reverse before joining.
ord(c) - 48 is ord(c) - ord('0'); both are fine, and the named form is clearer if you are not certain 48 is ASCII zero.
Dry Run
s = "456", t = "77"
i=2 j=1 carry=0 d = 0 + 6 + 7 = 13 write 3, carry 1 res=[3]
i=1 j=0 carry=1 d = 1 + 5 + 7 = 13 write 3, carry 1 res=[3,3]
i=0 j<0 carry=1 d = 1 + 4 = 5 write 5, carry 0 res=[3,3,5]
i<0 j<0 carry=0 loop ends
reversed -> "533"Row three is the length mismatch handled with no special case: t is exhausted, so only s contributes. And "1" + "9" shows the other ending — after both strings run out, carry = 1 keeps the loop alive for one more pass and produces "10".
Complexity
- Time — O(max(n, m)): one pass over the longer string, constant work per digit, plus the reverse.
- Space — O(max(n, m)): the output, which is at most one digit longer than the longer input. That is the result rather than scratch space, so by the usual convention the auxiliary cost is O(1) — worth saying, since "O(n) space" invites the question of whether it can be done in less, and it cannot: the answer itself is that long.
Common Pitfalls
- Dropping the final carry.
"999" + "1"must give"1000"; a loop conditioned only on the indices stops one digit early. - Padding the shorter string with zeros first. It works but allocates, and the
i >= 0guard already covers it. - Building the result with string concatenation in a loop. In most languages that is O(n^2) because each concatenation copies; collect into a list and join once.
- Forgetting to reverse. Digits come out least-significant first.
- Converting to int "just for the small cases". The inputs reach 10^4 digits, so there is no small case to special-case.
- Assuming leading zeros need stripping. The constraints rule them out of the input, and this construction never produces one except for the single digit
"0".
Full Solution — all languages
class Solution:
def addStrings(self, s, t):
i, j, carry = len(s) - 1, len(t) - 1, 0
res = []
while i >= 0 or j >= 0 or carry:
d = carry
if i >= 0:
d += ord(s[i]) - 48
i -= 1
if j >= 0:
d += ord(t[j]) - 48
j -= 1
res.append(chr(d % 10 + 48))
carry = d // 10
return "".join(reversed(res))import java.util.*;
class Solution {
public String addStrings(String s, String t) {
StringBuilder sb = new StringBuilder();
int i = s.length() - 1, j = t.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int d = carry;
if (i >= 0) d += s.charAt(i--) - '0';
if (j >= 0) d += t.charAt(j--) - '0';
sb.append((char) (d % 10 + '0'));
carry = d / 10;
}
return sb.reverse().toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string addStrings(string s, string t) {
string res;
int i = (int)s.size() - 1, j = (int)t.size() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int d = carry;
if (i >= 0) d += s[i--] - '0';
if (j >= 0) d += t[j--] - '0';
res += char(d % 10 + '0');
carry = d / 10;
}
reverse(res.begin(), res.end());
return res;
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var addStrings = function(s, t) {
let i = s.length - 1, j = t.length - 1, carry = 0, res = '';
while (i >= 0 || j >= 0 || carry > 0) {
let d = carry;
if (i >= 0) d += s.charCodeAt(i--) - 48;
if (j >= 0) d += t.charCodeAt(j--) - 48;
res = String(d % 10) + res;
carry = Math.floor(d / 10);
}
return res;
};