VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-two-large-numbers/

⇱ Sum of two large numbers as Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of two large numbers as Strings

Last Updated : 28 Mar, 2025

Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers.

Examples:

Input: s1 = "23", s2 = "25"
Output: "48"

Input: s1 = "00", s2 = "000"
Output: "0"

Input: s1 = "10000000", s2 = "89990000"
Output: 99990000

One by One Adding Digits

The idea is to add two large numbers represented as strings by simulating the manual addition process. We traverse the strings from the end, adding corresponding digits along with a carry, building the result digit by digit.

Step by step approach:

  1. Start from the rightmost digit of both input strings:
    • Add corresponding digits along with any existing carry.
    • Generate current digit of result by taking modulo 10 of sum.
    • Update carry for next iteration by integer division by 10.
  2. Continue adding until all digits and carry are processed.
  3. Reverse the resultant string. Reversing is necessary because we build the number from right to left (least significant digit first), but we want to display and return the number in its natural left-to-right representation.

Output
48

Time Complexity: O(n + m), as both strings are traversed only once
Space Complexity: O(max(n, m)), to store the resultant string.

Using Language Support (Java, Python, and JavaScript)


Comment