LeetCodee

415. Add Strings

Jump to Solution: Python Java C++ JavaScript C#

Problem Description

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

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⁴
  • num1 and num2 consist of only digits.
  • num1 and num2 don't have any leading zeros except for the zero itself.

Solution

Python Solution

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        # Initialize pointers and carry
        i = len(num1) - 1
        j = len(num2) - 1
        carry = 0
        result = []
        
        # Process digits from right to left
        while i >= 0 or j >= 0 or carry:
            # Get digits or use 0 if exhausted
            x = int(num1[i]) if i >= 0 else 0
            y = int(num2[j]) if j >= 0 else 0
            
            # Calculate sum and carry
            total = x + y + carry
            carry = total // 10
            digit = total % 10
            
            # Add digit to result
            result.append(str(digit))
            
            # Move pointers
            i -= 1
            j -= 1
        
        # Reverse and join the result
        return ''.join(result[::-1])

Time Complexity: O(max(n, m))

Where n and m are the lengths of num1 and num2 respectively.

Space Complexity: O(max(n, m))

For storing the result string.

Java Solution

class Solution {
    public String addStrings(String num1, String num2) {
        // Initialize pointers and carry
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;
        StringBuilder result = new StringBuilder();
        
        // Process digits from right to left
        while (i >= 0 || j >= 0 || carry > 0) {
            // Get digits or use 0 if exhausted
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            
            // Calculate sum and carry
            int total = x + y + carry;
            carry = total / 10;
            int digit = total % 10;
            
            // Add digit to result
            result.append(digit);
            
            // Move pointers
            i--;
            j--;
        }
        
        // Reverse and return the result
        return result.reverse().toString();
    }
}

Time Complexity: O(max(n, m))

Where n and m are the lengths of num1 and num2 respectively.

Space Complexity: O(max(n, m))

For storing the result string.

C++ Solution

class Solution {
public:
    string addStrings(string num1, string num2) {
        // Initialize pointers and carry
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;
        string result;
        
        // Process digits from right to left
        while (i >= 0 || j >= 0 || carry) {
            // Get digits or use 0 if exhausted
            int x = i >= 0 ? num1[i] - '0' : 0;
            int y = j >= 0 ? num2[j] - '0' : 0;
            
            // Calculate sum and carry
            int total = x + y + carry;
            carry = total / 10;
            int digit = total % 10;
            
            // Add digit to result
            result.push_back(digit + '0');
            
            // Move pointers
            i--;
            j--;
        }
        
        // Reverse and return the result
        reverse(result.begin(), result.end());
        return result;
    }
};

Time Complexity: O(max(n, m))

Where n and m are the lengths of num1 and num2 respectively.

Space Complexity: O(max(n, m))

For storing the result string.

JavaScript Solution

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var addStrings = function(num1, num2) {
    // Initialize pointers and carry
    let i = num1.length - 1;
    let j = num2.length - 1;
    let carry = 0;
    let result = [];
    
    // Process digits from right to left
    while (i >= 0 || j >= 0 || carry) {
        // Get digits or use 0 if exhausted
        const x = i >= 0 ? Number(num1[i]) : 0;
        const y = j >= 0 ? Number(num2[j]) : 0;
        
        // Calculate sum and carry
        const total = x + y + carry;
        carry = Math.floor(total / 10);
        const digit = total % 10;
        
        // Add digit to result
        result.push(digit);
        
        // Move pointers
        i--;
        j--;
    }
    
    // Reverse and join the result
    return result.reverse().join('');
};

Time Complexity: O(max(n, m))

Where n and m are the lengths of num1 and num2 respectively.

Space Complexity: O(max(n, m))

For storing the result array.

C# Solution

public class Solution {
    public string AddStrings(string num1, string num2) {
        // Initialize pointers and carry
        int i = num1.Length - 1;
        int j = num2.Length - 1;
        int carry = 0;
        StringBuilder result = new StringBuilder();
        
        // Process digits from right to left
        while (i >= 0 || j >= 0 || carry > 0) {
            // Get digits or use 0 if exhausted
            int x = i >= 0 ? num1[i] - '0' : 0;
            int y = j >= 0 ? num2[j] - '0' : 0;
            
            // Calculate sum and carry
            int total = x + y + carry;
            carry = total / 10;
            int digit = total % 10;
            
            // Add digit to result
            result.Append(digit);
            
            // Move pointers
            i--;
            j--;
        }
        
        // Get the characters and reverse them
        char[] chars = result.ToString().ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

Time Complexity: O(max(n, m))

Where n and m are the lengths of num1 and num2 respectively.

Space Complexity: O(max(n, m))

For storing the result string.

Approach Explanation

The solution uses a digit-by-digit addition approach:

  1. Key Insights:
    • String processing
    • Carry handling
    • Digit conversion
    • Result building
  2. Algorithm Steps:
    • Process digits
    • Handle carry
    • Build result
    • Reverse string

Implementation Details:

  • Pointer tracking
  • Digit extraction
  • Sum calculation
  • String building

Optimization Insights:

  • In-place addition
  • Minimal conversion
  • Efficient storage
  • Single pass

Edge Cases:

  • Different lengths
  • Zero values
  • Large numbers
  • Carry overflow