Add Strings

Given two non-negative integers num1 and num2 represented as strings, return the sum of these two numbers, also as a string. You must not use any built-in BigInteger library.

Example 1
Input: "11" + "123" → Output: "134"
Example 2
Input: "456" + "77" → Output: "533"

Solution Approach

Simulate grade-school addition from right to left, carrying over.

  • Two pointers at end of both strings, carry=0.
  • While i>=0 or j>=0 or carry>0: sum = carry + (num1[i] if valid) + (num2[j] if valid).
  • Append sum%10, carry = sum/10.
  • Reverse result.
Java
class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int i = num1.length()-1, j = num2.length()-1, carry = 0;
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0) sum += num1.charAt(i--) - '0';
            if (j >= 0) sum += num2.charAt(j--) - '0';
            sb.append(sum % 10);
            carry = sum / 10;
        }
        return sb.reverse().toString();
    }
}
  • Time Complexity: O(max(M,N))
  • Space Complexity: O(max(M,N))