Open In App

Sum of two large numbers as Strings

Last Updated : 28 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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.
C++
// C++ program to find sum of two large numbers
#include <bits/stdc++.h>
using namespace std;

string findSum(string &s1, string &s2) {
    
    // If one string is empty, return the other
    if (s1.empty()) return s2;
    if (s2.empty()) return s1;
    
    // Result string to store the sum
    string result = "";
    
    // Indices to traverse strings from end
    int i = s1.length() - 1;
    int j = s2.length() - 1;
    
    // Carry to handle digit sum > 9
    int carry = 0;
    
    // Traverse both strings from end
    while (i >= 0 || j >= 0 || carry > 0) {
        
        // Get current digits (0 if string exhausted)
        int digit1 = (i >= 0) ? s1[i] - '0' : 0;
        int digit2 = (j >= 0) ? s2[j] - '0' : 0;
        
        // Sum current digits and carry
        int sum = digit1 + digit2 + carry;
        
        // Update carry and current digit
        carry = sum / 10;
        sum %= 10;
        
        // Prepend current digit to result 
        // (we'll track leading zeros later)
        result.push_back(('0' + sum));
        
        // Move indices
        i--;
        j--;
    }
    
    // Remove leading zeros
    while (result.size() > 1 && result[result.size()-1]=='0') {
        result.pop_back();
    }
    
    // reverse the string 
    reverse(result.begin(), result.end());
    
    return result;
}

int main() {
    string s1 = "25", s2 = "23";
    cout << findSum(s1, s2);
    return 0;
}
Java
// Java program to find sum of two large numbers
import java.util.*;

class GfG {
    
    static String findSum(String s1, String s2) {
        
        // If one string is empty, return the other
        if (s1.isEmpty()) return s2;
        if (s2.isEmpty()) return s1;
        
        // Result string to store the sum
        StringBuilder result = new StringBuilder();
        
        // Indices to traverse strings from end
        int i = s1.length() - 1;
        int j = s2.length() - 1;
        
        // Carry to handle digit sum > 9
        int carry = 0;
        
        // Traverse both strings from end
        while (i >= 0 || j >= 0 || carry > 0) {
            
            // Get current digits (0 if string exhausted)
            int digit1 = (i >= 0) ? s1.charAt(i) - '0' : 0;
            int digit2 = (j >= 0) ? s2.charAt(j) - '0' : 0;
            
            // Sum current digits and carry
            int sum = digit1 + digit2 + carry;
            
            // Update carry and current digit
            carry = sum / 10;
            sum %= 10;
            
            // Prepend current digit to result 
            result.append((char) ('0' + sum));
            
            // Move indices
            i--;
            j--;
        }
        
        // Remove leading zeros
        while (result.length() > 1 && result.charAt(result.length() - 1) == '0') {
            result.deleteCharAt(result.length() - 1);
        }
        
        // Reverse the string 
        result.reverse();
        
        return result.toString();
    }

    public static void main(String[] args) {
        String s1 = "25", s2 = "23";
        System.out.println(findSum(s1, s2));
    }
}
Python
# Python program to find sum of two large numbers

def findSum(s1, s2):
    
    # If one string is empty, return the other
    if not s1:
        return s2
    if not s2:
        return s1
    
    # Result string to store the sum
    result = []
    
    # Indices to traverse strings from end
    i = len(s1) - 1
    j = len(s2) - 1
    
    # Carry to handle digit sum > 9
    carry = 0
    
    # Traverse both strings from end
    while i >= 0 or j >= 0 or carry > 0:
        
        # Get current digits (0 if string exhausted)
        digit1 = int(s1[i]) if i >= 0 else 0
        digit2 = int(s2[j]) if j >= 0 else 0
        
        # Sum current digits and carry
        digitSum = digit1 + digit2 + carry
        
        # Update carry and current digit
        carry = digitSum // 10
        digitSum %= 10
        
        # Append current digit to result 
        result.append(str(digitSum))
        
        # Move indices
        i -= 1
        j -= 1
    
    # Remove leading zeros
    while len(result) > 1 and result[-1] == '0':
        result.pop()
    
    # Reverse the string 
    return ''.join(result[::-1])

if __name__ == "__main__":
    s1 = "25"
    s2 = "23"
    print(findSum(s1, s2))
C#
// C# program to find sum of two large numbers
using System;
using System.Text;

class GfG {
    
    static string findSum(string s1, string s2) {
        
        // If one string is empty, return the other
        if (s1.Length == 0) return s2;
        if (s2.Length == 0) return s1;
        
        // Result string to store the sum
        StringBuilder result = new StringBuilder();
        
        // Indices to traverse strings from end
        int i = s1.Length - 1;
        int j = s2.Length - 1;
        
        // Carry to handle digit sum > 9
        int carry = 0;
        
        // Traverse both strings from end
        while (i >= 0 || j >= 0 || carry > 0) {
            
            // Get current digits (0 if string exhausted)
            int digit1 = (i >= 0) ? s1[i] - '0' : 0;
            int digit2 = (j >= 0) ? s2[j] - '0' : 0;
            
            // Sum current digits and carry
            int sum = digit1 + digit2 + carry;
            
            // Update carry and current digit
            carry = sum / 10;
            sum %= 10;
            
            // Append current digit to result 
            result.Append((char) ('0' + sum));
            
            // Move indices
            i--;
            j--;
        }
        
        // Remove leading zeros
        while (result.Length > 1 && result[result.Length - 1] == '0') {
            result.Length--;
        }
        
        // Reverse the string 
        char[] charArray = result.ToString().ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }

    static void Main() {
        string s1 = "25", s2 = "23";
        Console.WriteLine(findSum(s1, s2));
    }
}
JavaScript
// JavaScript program to find sum of two large numbers

function findSum(s1, s2) {
    
    // If one string is empty, return the other
    if (s1.length === 0) return s2;
    if (s2.length === 0) return s1;
    
    // Result string to store the sum
    let result = [];
    
    // Indices to traverse strings from end
    let i = s1.length - 1;
    let j = s2.length - 1;
    
    // Carry to handle digit sum > 9
    let carry = 0;
    
    // Traverse both strings from end
    while (i >= 0 || j >= 0 || carry > 0) {
        
        // Get current digits (0 if string exhausted)
        let digit1 = (i >= 0) ? s1[i] - '0' : 0;
        let digit2 = (j >= 0) ? s2[j] - '0' : 0;
        
        // Sum current digits and carry
        let sum = digit1 + digit2 + carry;
        
        // Update carry and current digit
        carry = Math.floor(sum / 10);
        sum %= 10;
        
        // Append current digit to result 
        result.push(sum.toString());
        
        // Move indices
        i--;
        j--;
    }
    
    // Remove leading zeros
    while (result.length > 1 && result[result.length - 1] === '0') {
        result.pop();
    }
    
    // Reverse the string 
    return result.reverse().join('');
}

let s1 = "25", s2 = "23";
console.log(findSum(s1, s2));

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)

Java
import java.util.*;
import java.math.*;
public class GFG{

	public static void main(String []args){
		String s1 = "7777555511111111";
		String s2 = "3332222221111";
		
		BigInteger a = new BigInteger(s1); 
		BigInteger b = new BigInteger(s2);
		
		System.out.println(a.add(b)); 
		
	}
}
Python
# Importing the required library
from decimal import Decimal

s1 = '7777555511111111'
s2 = '3332222221111'

a = Decimal(s1) 
b = Decimal(s2)  

print(a + b)  
JavaScript
const s1 = '7777555511111111';
const s2 = '3332222221111';

const a = BigInt(s1);
const b = BigInt(s2);

console.log(a + b);  



Next Article

Similar Reads