Browse curriculum

Add Strings (LeetCode 415)

Add Strings (LeetCode 415): add two non-negative numbers given as strings with two pointers from the right and a carry, without converting them to integers.

Problem Understanding

Add Strings: given two non-negative integers num1 and num2 as strings, return their sum as a string. You may not use a big-integer library or convert the inputs to integers directly.

Examples: "11" + "123" = "134", "456" + "77" = "533", and "0" + "0" = "0".

The Intuition: Column Addition, Right to Left

Add the numbers the way you would on paper:

  1. Point i and j at the last digit of each string.
  2. A column's total is the carry plus the digits there, at most 1 + 9 + 9 = 19.
  3. The digit to write is total % 10, and the carry into the next column is total / 10.
  4. When one string runs out, treat its digits as 0; when both run out, a leftover carry still adds a digit.

It is the two pointers idea run from the ends of two strings at once, exactly Add Binary in base 10. Multiply Strings extends the same carry handling to every digit pair.

Add Strings Visualization

COLUMNS COUNT FROM THE RIGHT · CARRY SHOWN ABOVE THE NEXT COLUMN

START AT THE RIGHT

carry

num1

4
5
6

num2

7
7

sum

carry

0

sum

:

 

Start at the last digit of each string: i = 2, j = 1, carry = 0

Next

Column 0: carry 0 + num1 6 + num2 7 = 13. Write 3, carry 1

Free preview: the first 3 of 5 steps

num1

num2

num1 and num2 are right-aligned above the sum, with the carry shown over the next column. Try Carry chain to watch a carry ripple through every column and add a new digit at the front.

Add Strings Dry Run

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

Column num1 digit num2 digit carry in total write carry out
0 6 7 0 13 3 1
1 5 7 1 13 3 1
2 4 - 1 5 5 0

Answer: written right to left 3, 3, 5, reversed: "533".

Add Strings LeetCode Solution

One loop that runs while either string has digits or a carry is left. Digits are converted one character at a time. C fills a buffer from the end and then shifts the answer to the front so the returned pointer can be freed.

Add Strings Code
1var addStrings = function(num1, num2) {
2 let i = num1.length - 1, j = num2.length - 1, carry = 0;
3 const out = [];
4 while (i >= 0 || j >= 0 || carry) {
5 let total = carry;
6 if (i >= 0) total += num1.charCodeAt(i--) - 48;
7 if (j >= 0) total += num2.charCodeAt(j--) - 48;
8 out.push(total % 10);
9 carry = Math.floor(total / 10);
10 }
11 return out.reverse().join('');
12};

Add Strings in Python, Java, C++, TypeScript and C

Add Strings in Python
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        out = []
        while i >= 0 or j >= 0 or carry:
            total = carry
            if i >= 0:
                total += ord(num1[i]) - ord('0')
                i -= 1
            if j >= 0:
                total += ord(num2[j]) - ord('0')
                j -= 1
            out.append(str(total % 10))
            carry = total // 10
        return ''.join(reversed(out))
Add Strings in Java
class Solution {
    public String addStrings(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
        StringBuilder sb = new StringBuilder();
        while (i >= 0 || j >= 0 || carry > 0) {
            int total = carry;
            if (i >= 0) total += num1.charAt(i--) - '0';
            if (j >= 0) total += num2.charAt(j--) - '0';
            sb.append(total % 10);
            carry = total / 10;
        }
        return sb.reverse().toString();
    }
}
Add Strings in C++
class Solution {
public:
    string addStrings(string num1, string num2) {
        int i = num1.size() - 1, j = num2.size() - 1, carry = 0;
        string out;
        while (i >= 0 || j >= 0 || carry) {
            int total = carry;
            if (i >= 0) total += num1[i--] - '0';
            if (j >= 0) total += num2[j--] - '0';
            out.push_back('0' + total % 10);
            carry = total / 10;
        }
        reverse(out.begin(), out.end());
        return out;
    }
};
Add Strings in TypeScript
function addStrings(num1: string, num2: string): string {
    let i = num1.length - 1, j = num2.length - 1, carry = 0;
    const out: number[] = [];
    while (i >= 0 || j >= 0 || carry) {
        let total = carry;
        if (i >= 0) total += num1.charCodeAt(i--) - 48;
        if (j >= 0) total += num2.charCodeAt(j--) - 48;
        out.push(total % 10);
        carry = Math.floor(total / 10);
    }
    return out.reverse().join('');
}
Add Strings in C
char* addStrings(char* num1, char* num2) {
    int i = strlen(num1) - 1, j = strlen(num2) - 1, carry = 0;
    int len = (i > j ? i : j) + 2;
    char* out = malloc(len + 1);
    out[len] = '\0';
    int k = len - 1;
    while (i >= 0 || j >= 0 || carry) {
        int total = carry;
        if (i >= 0) total += num1[i--] - '0';
        if (j >= 0) total += num2[j--] - '0';
        out[k--] = '0' + total % 10;
        carry = total / 10;
    }
    memmove(out, out + k + 1, len - k);
    return out;
}

Edge Cases & Common Mistakes

  • Final carry: "999" + "1" is "1000"; keep looping while the carry is not 0.
  • Different lengths: once a string is used up, add only the other digit and the carry.
  • Both zero: "0" + "0" is "0".
  • Converting the whole string: int(num1) is not allowed, and overflows in fixed-width languages for long inputs.
  • Prepending each digit: O(n²) on immutable strings; append, then reverse once.

Summary

Walk both strings from the right with a carry. Each column writes total % 10 and carries total / 10; keep going while either string has digits or the carry is not 0. Reverse the written digits. O(max(m, n)) time and space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Point at the last digits

    i = len(num1) - 1, j = len(num2) - 1, carry = 0.

  2. Add one column at a time

    total = carry plus num1[i] and num2[j] when they exist. Append total % 10, set carry = total / 10, move both indices left.

  3. Finish

    Stop when both indices are past the start and the carry is 0, then reverse the result.

Frequently asked questions

How do you add two numbers stored as strings?

Start two indices at the last digit of each string. In each column add the carry and whichever digits are still there. Write total % 10 and carry total / 10. Continue while either index is valid or the carry is not 0, then reverse the written digits.


How do you turn a digit character into a number without int()?

Subtract the code of '0': '7' - '0' is 7 in Java, C++ and C, ord(c) - ord('0') in Python, and c.charCodeAt(0) - 48 in JavaScript. LeetCode forbids converting the whole string, not single digits.


How is Add Strings different from Add Binary?

Only the base. Add Binary writes total % 2 and carries total / 2; Add Strings writes total % 10 and carries total / 10. The two-pointer loop and the final carry check are identical.

New to the technique behind this problem? Watch it run step by step:

Two Pointers Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description