Add two numbers represented by two arrays - GeeksforGeeks

19 Mar, 2021
Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337. Examples : 
Input : n = 3, m = 3
        a[] = { 1, 2, 3 }
        b[] = { 2, 1, 4 }
Output : 337
123 + 214 = 337

Input : n = 4, m = 3
        a[] = { 9, 5, 4, 9 }
        b[] = { 2, 1, 4 }
Output : 9763
The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum. While adding 0th index element if the carry left, then append it to beginning of the number. Below is the illustration of approach:  
Below is the implementation of this approach:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to sum two numbers represented two// arrays.#include <bits/stdc++.h>using namespace std; // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionint calSumUtil(int a[], int b[], int n, int m){    // array to store sum.    int sum[n];     int i = n - 1, j = m - 1, k = n - 1;     int carry = 0, s = 0;     // Until we reach beginning of array.    // we are comparing only for second array    // because we have already compare the size    // of array in wrapper function.    while (j >= 0) {         // find sum of corresponding element        // of both arrays.        s = a[i] + b[j] + carry;        sum[k] = (s % 10);         // Finding carry for next sum.        carry = s / 10;         k--;        i--;        j--;    }     // If second array size is less the first    // array size.    while (i >= 0) {         // Add carry to first array elements.        s = a[i] + carry;        sum[k] = (s % 10);        carry = s / 10;         i--;        k--;    }     int ans = 0;     // If there is carry on adding 0 index elements.    // append 1 to total sum.    if (carry)        ans = 10;     // Converting array into number.    for (int i = 0; i <= n - 1; i++) {        ans += sum[i];        ans *= 10;    }     return ans / 10;} // Wrapper Functionint calSum(int a[], int b[], int n, int m){    // Making first array which have    // greater number of element    if (n >= m)        return calSumUtil(a, b, n, m);     else        return calSumUtil(b, a, m, n);} // Driven Programint main(){    int a[] = { 9, 3, 9 };    int b[] = { 6, 1 };     int n = sizeof(a) / sizeof(a[0]);    int m = sizeof(b) / sizeof(b[0]);     cout << calSum(a, b, n, m) << endl;     return 0;}
// Java program to sum two numbers // represented two arrays.import java.io.*; class GFG {     // Return sum of two number represented by    // the arrays. Size of a[] is greater than    // b[]. It is made sure be the wrapper    // function    static int calSumUtil(int a[], int b[],                                int n, int m)    {        // array to store sum.        int[] sum= new int[n];             int i = n - 1, j = m - 1, k = n - 1;             int carry = 0, s = 0;             // Until we reach beginning of array.        // we are comparing only for second        // array because we have already compare        // the size of array in wrapper function.        while (j >= 0)        {            // find sum of corresponding element            // of both array.            s = a[i] + b[j] + carry;                         sum[k] = (s % 10);                 // Finding carry for next sum.            carry = s / 10;                 k--;            i--;            j--;        }             // If second array size is less        // the first array size.        while (i >= 0)        {            // Add carry to first array elements.            s = a[i] + carry;            sum[k] = (s % 10);            carry = s / 10;                 i--;            k--;        }             int ans = 0;             // If there is carry on adding 0 index        // elements  append 1 to total sum.        if (carry == 1)            ans = 10;             // Converting array into number.        for ( i = 0; i <= n - 1; i++) {            ans += sum[i];            ans *= 10;        }             return ans / 10;    }         // Wrapper Function    static int calSum(int a[], int b[], int n,                                        int m)    {        // Making first array which have        // greater number of element        if (n >= m)            return calSumUtil(a, b, n, m);             else            return calSumUtil(b, a, m, n);    }         /* Driver program to test above function */    public static void main(String[] args)    {        int a[] = { 9, 3, 9 };            int b[] = { 6, 1 };                     int n = a.length;            int m = b.length;        System.out.println(calSum(a, b, n, m));    }} // This article is contributed by Gitanjali.
# Python3 code to sum two numbers# representer two arrays. # Return sum of two number represented# by the arrays. Size of a[] is greater# than b[]. It is made sure be the# wrapper functiondef calSumUtil( a , b , n , m ):    # array to store sum.    sum = [0] * n    i = n - 1    j = m - 1    k = n - 1         carry = 0    s = 0         # Until we reach beginning of array.    # we are comparing only for second array    # because we have already compare the size    # of array in wrapper function.    while j >= 0:         # find sum of corresponding element        # of both array.        s = a[i] + b[j] + carry        sum[k] = (s % 10)                 # Finding carry for next sum.        carry = s // 10                 k-=1        i-=1        j-=1         # If second array size is less the first    # array size.    while i >= 0:         # Add carry to first array elements.        s = a[i] + carry        sum[k] = (s % 10)        carry = s // 10                 i-=1        k-=1         ans = 0    # If there is carry on adding 0 index elements.    # append 1 to total sum.    if carry:        ans = 10         # Converting array into number.    for i in range(n):        ans += sum[i]        ans *= 10         return ans // 10 # Wrapper Functiondef calSum(a, b, n, m ):     # Making first array which have    # greater number of element    if n >= m:        return calSumUtil(a, b, n, m)    else:        return calSumUtil(b, a, m, n) # Driven Codea = [ 9, 3, 9 ]b = [ 6, 1 ]n = len(a)m = len(b)print(calSum(a, b, n, m)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to sum two numbers// represented two arrays.using System; class GFG {     // Return sum of two number represented by    // the arrays. Size of a[] is greater than    // b[]. It is made sure be the wrapper    // function    static int calSumUtil(int []a, int []b,                                int n, int m)    {        // array to store sum.        int[] sum= new int[n];             int i = n - 1, j = m - 1, k = n - 1;             int carry = 0, s = 0;             // Until we reach beginning of array.        // we are comparing only for second        // array because we have already compare        // the size of array in wrapper function.        while (j >= 0)        {            // find sum of corresponding element            // of both array.            s = a[i] + b[j] + carry;                         sum[k] = (s % 10);                 // Finding carry for next sum.            carry = s / 10;                 k--;            i--;            j--;        }             // If second array size is less        // the first array size.        while (i >= 0)        {            // Add carry to first array elements.            s = a[i] + carry;            sum[k] = (s % 10);            carry = s / 10;                 i--;            k--;        }             int ans = 0;             // If there is carry on adding 0 index        // elements append 1 to total sum.        if (carry == 1)            ans = 10;             // Converting array into number.        for ( i = 0; i <= n - 1; i++) {            ans += sum[i];            ans *= 10;        }             return ans / 10;    }         // Wrapper Function    static int calSum(int []a, int []b, int n,                                        int m)    {        // Making first array which have        // greater number of element        if (n >= m)            return calSumUtil(a, b, n, m);             else            return calSumUtil(b, a, m, n);    }         // Driver program    public static void Main()    {        int []a = { 9, 3, 9 };        int []b = { 6, 1 };                 int n = a.Length;             int m = b.Length;        Console.WriteLine(calSum(a, b, n, m));    }} // This article is contributed by vt_m.
<?php// PHP program to sum two numbers// represented two arrays.  // Return sum of two number represented// by the arrays. Size of a[] is greater// than b[]. It is made sure be the// wrapper functionfunction calSumUtil($a, $b, $n, $m){    // array to store sum.    $sum = array();     $i = $n - 1; $j = $m - 1; $k = $n - 1;     $carry = 0; $s = 0;     // Until we reach beginning of array.    // we are comparing only for second array    // because we have already compare the size    // of array in wrapper function.    while ($j >= 0)    {        // find sum of corresponding        // element of both array.        $s = $a[$i] + $b[$j] + $carry;        $sum[$k] = ($s % 10);         // Finding carry for next sum.        $carry = $s / 10;         $k--;        $i--;        $j--;    }     // If second array size is less    // than the first array size.    while ($i >= 0)    {        // Add carry to first array elements.        $s = $a[$i] + $carry;        $sum[$k] = ($s % 10);        $carry = $s / 10;         $i--;        $k--;    }     $ans = 0;     // If there is carry on    // adding 0 index elements.    // append 1 to total sum.    if ($carry)        $ans = 10;     // Converting array into number.    for ( $i = 0; $i <= $n - 1; $i++)    {        $ans += $sum[$i];        $ans *= 10;    }     return $ans / 10;} // Wrapper Functionfunction calSum( $a, $b, $n, $m){    // Making first array which have    // greater number of element    if ($n >= $m)        return calSumUtil($a, $b, $n, $m);     else        return calSumUtil($b, $a, $m, $n);} // Driven Code$a = array( 9, 3, 9 );$b = array( 6, 1 ); $n = count($a);$m = count($b); echo calSum($a, $b, $n, $m); // This article is contributed by anuj_67.?>
<script> // Javascript program to sum two numbers represented two// arrays. // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionfunction calSumUtil(a, b, n, m){     // array to store sum.    let sum = new Array(n);    let i = n - 1, j = m - 1, k = n - 1;    let carry = 0, s = 0;     // Until we reach beginning of array.    // we are comparing only for second array    // because we have already compare the size    // of array in wrapper function.    while (j >= 0) {         // find sum of corresponding element        // of both arrays.        s = a[i] + b[j] + carry;        sum[k] = (s % 10);         // Finding carry for next sum.        carry = Math.floor(s / 10);         k--;        i--;        j--;    }     // If second array size is less the first    // array size.    while (i >= 0) {         // Add carry to first array elements.        s = a[i] + carry;        sum[k] = (s % 10);        carry = Math.floor(s / 10);         i--;        k--;    }     let ans = 0;     // If there is carry on adding 0 index elements.    // append 1 to total sum.    if (carry)        ans = 10;     // Converting array into number.    for (let i = 0; i <= n - 1; i++) {        ans += sum[i];        ans *= 10;    }     return ans / 10;} // Wrapper Functionfunction calSum(a, b, n, m){     // Making first array which have    // greater number of element    if (n >= m)        return calSumUtil(a, b, n, m);     else        return calSumUtil(b, a, m, n);} // Driven Program    let a = [ 9, 3, 9 ];    let b = [ 6, 1 ];     let n = a.length;    let m = b.length;     document.write(calSum(a, b, n, m) + "<br>");     // This code is contributed by Mayank Tyagi </script>
Output :  
1000
Time Complexity: O(n + m)
Auxiliary Space: O(max(n, m)) 
gautamkumar
vt_m
SonamKumari
subhammahato348
mayanktyagi1709
large-numbers
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack