Open In App

Add two numbers represented by two arrays

Last Updated : 14 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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 function
int 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 Function
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);
}
 
// Driven Program
int 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




// 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));
    }
}
 
//


Python3




# 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 function
def 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 Function
def 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 = [ 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#




// 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.


Javascript




<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 function
function 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 Function
function 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>


PHP




<?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 function
function 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 Function
function 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.
?>


Output

1000





Time Complexity: O(n + m)
Auxiliary Space: O(max(n, m))

Approach 2:  Iterative approach:

The function  “addArrays” that takes two arrays of integers “arr1” and “arr2” of sizes “n” and “m” respectively.

 And it returns a vector that contains the sum of the two arrays. The addition is performed digit-by-digit, starting from the rightmost digit of each arrays, and any carry is propagated to the next digit.

The implementation use a typical algorithm for digit-by-digit addition of two numbers. The corresponding digits from the two arrays are added, along with any carries from earlier additions, beginning with the rightmost digit of each array. The remainder is added to the result vector after the sum is divided by 10 to determine the carry for the following addition. The procedure is repeated until the final carry and all digits of the two arrays are added.

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
vector<int> addArrays(int arr1[], int arr2[], int n, int m) {
    // Initialize the result vector to store the sum
    vector<int> result;
 
    // Initialize the carry variable to 0
    int carry = 0;
 
    // Loop through the arrays from right to left
    for (int i = n-1, j = m-1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
        // Calculate the sum of the corresponding digits in the arrays
        int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
 
        // Calculate the carry, if any, to be added to the next sum
        carry = sum / 10;
 
        // Calculate the digit to be added to the result vector
        int digit = sum % 10;
 
        // Add the digit to the result vector
        result.insert(result.begin(), digit);
    }
 
    // Return the result vector
    return result;
}
 
int main() {
    // Initialize the input arrays
    int arr1[] = {9, 5, 4, 9};
    int arr2[] = {2, 1, 4};
 
    // Get the sizes of the arrays
    int n = sizeof(arr1)/sizeof(arr1[0]);
    int m = sizeof(arr2)/sizeof(arr2[0]);
 
    // Calculate the sum of the arrays and store it in the result vector
    vector<int> result = addArrays(arr1, arr2, n, m);
 
    // Print the result vector
    for (int i = 0; i < result.size(); i++) {
        cout << result[i];
    }
    cout << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
 
public class AddArrays {
    public static ArrayList<Integer> addArrays(int[] arr1, int[] arr2) {
        // Initialize the result vector to store the sum
        ArrayList<Integer> result = new ArrayList<>();
 
        int n = arr1.length;
        int m = arr2.length;
         
        // Initialize the carry variable to 0
        int carry = 0;
         
        // Loop through the arrays from right to left
        for (int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
             
            // Calculate the sum of the corresponding digits in the arrays
            int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
           
            // Calculate the carry, if any, to be added to the next sum
            carry = sum / 10;
           
            // Calculate the digit to be added to the result vector
            int digit = sum % 10;
             
            // Add the digit to the result vector
            result.add(0, digit);
        }
 
        return result;
    }
 
    public static void main(String[] args) {
         
        // Initialize the input arrays
        int[] arr1 = {9, 5, 4, 9};
        int[] arr2 = {2, 1, 4};
         
        // Calculate the sum of the arrays and store it in the result vector
        ArrayList<Integer> result = addArrays(arr1, arr2);
 
        for (int num : result) {
            System.out.print(num);
        }
        System.out.println();
    }
}


Python




# code
def add_arrays(arr1, arr2):
    n, m = len(arr1), len(arr2)
    result = []
    carry = 0
    i, j = n-1, m-1
     
    while i >= 0 or j >= 0 or carry > 0:
        sum = (arr1[i] if i >= 0 else 0) + (arr2[j] if j >= 0 else 0) + carry
        carry = sum // 10
        digit = sum % 10
        result.insert(0, digit)
        i -= 1
        j -= 1
     
    return result
 
# Example usage
arr1 = [9, 5, 4, 9]
arr2 = [2, 1, 4]
result = add_arrays(arr1, arr2)
print(result)


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static List<int> AddArrays(int[] arr1, int[] arr2, int n, int m)
    {
        // Initialize the result list to store the sum
        List<int> result = new List<int>();
 
        // Initialize the carry variable to 0
        int carry = 0;
 
        // Loop through the arrays from right to left
        for (int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--)
        {
            // Calculate the sum of the corresponding digits in the arrays
            int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
 
            // Calculate the carry, if any, to be added to the next sum
            carry = sum / 10;
 
            // Calculate the digit to be added to the result list
            int digit = sum % 10;
 
            // Add the digit to the result list
            result.Insert(0, digit);
        }
 
        // Return the result list
        return result;
    }
 
    static void Main()
    {
        // Initialize the input arrays
        int[] arr1 = { 9, 5, 4, 9 };
        int[] arr2 = { 2, 1, 4 };
 
        // Get the sizes of the arrays
        int n = arr1.Length;
        int m = arr2.Length;
 
        // Calculate the sum of the arrays and store it in the result list
        List<int> result = AddArrays(arr1, arr2, n, m);
 
        // Print the result list
        foreach (int digit in result)
        {
            Console.Write(digit);
        }
        Console.WriteLine();
    }
}


Javascript




function addArrays(arr1, arr2) {
    // Initialize the result array to store the sum
    const result = [];
 
    // Initialize the carry variable to 0
    let carry = 0;
 
    // Get the lengths of the input arrays
    const n = arr1.length;
    const m = arr2.length;
 
    // Loop through the arrays from right to left
    for (let i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
        // Calculate the sum of the corresponding digits in the arrays
        const sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
 
        // Calculate the carry, if any, to be added to the next sum
        carry = Math.floor(sum / 10);
 
        // Calculate the digit to be added to the result array
        const digit = sum % 10;
 
        // Add the digit to the beginning of the result array
        result.unshift(digit);
    }
 
    // Return the result array
    return result;
}
 
// Initialize the input arrays
const arr1 = [9, 5, 4, 9];
const arr2 = [2, 1, 4];
 
// Calculate the sum of the arrays and store it in the result array
const result = addArrays(arr1, arr2);
 
// Print the result array
console.log(result.join('')); // Join the digits and print
 
// This code is contributed by shivamgupta310570


Output

9763





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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads