Add two numbers represented by two arrays
Last Updated :
14 Oct, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int calSumUtil( int a[], int b[], int n, int m)
{
int sum[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
while (j >= 0) {
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
carry = s / 10;
k--;
i--;
j--;
}
while (i >= 0) {
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
}
int ans = 0;
if (carry)
ans = 10;
for ( int i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
int calSum( int a[], int b[], int n, int m)
{
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
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
import java.io.*;
class GFG {
static int calSumUtil( int a[], int b[],
int n, int m)
{
int [] sum= new int [n];
int i = n - 1 , j = m - 1 , k = n - 1 ;
int carry = 0 , s = 0 ;
while (j >= 0 )
{
s = a[i] + b[j] + carry;
sum[k] = (s % 10 );
carry = s / 10 ;
k--;
i--;
j--;
}
while (i >= 0 )
{
s = a[i] + carry;
sum[k] = (s % 10 );
carry = s / 10 ;
i--;
k--;
}
int ans = 0 ;
if (carry == 1 )
ans = 10 ;
for ( i = 0 ; i <= n - 1 ; i++) {
ans += sum[i];
ans *= 10 ;
}
return ans / 10 ;
}
static int calSum( int a[], int b[], int n,
int m)
{
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
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
def calSumUtil( a , b , n , m ):
sum = [ 0 ] * n
i = n - 1
j = m - 1
k = n - 1
carry = 0
s = 0
while j > = 0 :
s = a[i] + b[j] + carry
sum [k] = (s % 10 )
carry = s / / 10
k - = 1
i - = 1
j - = 1
while i > = 0 :
s = a[i] + carry
sum [k] = (s % 10 )
carry = s / / 10
i - = 1
k - = 1
ans = 0
if carry:
ans = 10
for i in range (n):
ans + = sum [i]
ans * = 10
return ans / / 10
def calSum(a, b, n, m ):
if n > = m:
return calSumUtil(a, b, n, m)
else :
return calSumUtil(b, a, m, n)
a = [ 9 , 3 , 9 ]
b = [ 6 , 1 ]
n = len (a)
m = len (b)
print (calSum(a, b, n, m))
|
C#
using System;
class GFG {
static int calSumUtil( int []a, int []b,
int n, int m)
{
int [] sum= new int [n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
while (j >= 0)
{
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
carry = s / 10;
k--;
i--;
j--;
}
while (i >= 0)
{
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
}
int ans = 0;
if (carry == 1)
ans = 10;
for ( i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
static int calSum( int []a, int []b, int n,
int m)
{
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
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));
}
}
|
Javascript
<script>
function calSumUtil(a, b, n, m)
{
let sum = new Array(n);
let i = n - 1, j = m - 1, k = n - 1;
let carry = 0, s = 0;
while (j >= 0) {
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
carry = Math.floor(s / 10);
k--;
i--;
j--;
}
while (i >= 0) {
s = a[i] + carry;
sum[k] = (s % 10);
carry = Math.floor(s / 10);
i--;
k--;
}
let ans = 0;
if (carry)
ans = 10;
for (let i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
function calSum(a, b, n, m)
{
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
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>" );
</script>
|
PHP
<?php
function calSumUtil( $a , $b , $n , $m )
{
$sum = array ();
$i = $n - 1; $j = $m - 1; $k = $n - 1;
$carry = 0; $s = 0;
while ( $j >= 0)
{
$s = $a [ $i ] + $b [ $j ] + $carry ;
$sum [ $k ] = ( $s % 10);
$carry = $s / 10;
$k --;
$i --;
$j --;
}
while ( $i >= 0)
{
$s = $a [ $i ] + $carry ;
$sum [ $k ] = ( $s % 10);
$carry = $s / 10;
$i --;
$k --;
}
$ans = 0;
if ( $carry )
$ans = 10;
for ( $i = 0; $i <= $n - 1; $i ++)
{
$ans += $sum [ $i ];
$ans *= 10;
}
return $ans / 10;
}
function calSum( $a , $b , $n , $m )
{
if ( $n >= $m )
return calSumUtil( $a , $b , $n , $m );
else
return calSumUtil( $b , $a , $m , $n );
}
$a = array ( 9, 3, 9 );
$b = array ( 6, 1 );
$n = count ( $a );
$m = count ( $b );
echo calSum( $a , $b , $n , $m );
?>
|
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) {
vector< int > result;
int carry = 0;
for ( int i = n-1, j = m-1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
carry = sum / 10;
int digit = sum % 10;
result.insert(result.begin(), digit);
}
return result;
}
int main() {
int arr1[] = {9, 5, 4, 9};
int arr2[] = {2, 1, 4};
int n = sizeof (arr1)/ sizeof (arr1[0]);
int m = sizeof (arr2)/ sizeof (arr2[0]);
vector< int > result = addArrays(arr1, arr2, n, m);
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) {
ArrayList<Integer> result = new ArrayList<>();
int n = arr1.length;
int m = arr2.length;
int carry = 0 ;
for ( int i = n - 1 , j = m - 1 ; i >= 0 || j >= 0 || carry > 0 ; i--, j--) {
int sum = (i >= 0 ? arr1[i] : 0 ) + (j >= 0 ? arr2[j] : 0 ) + carry;
carry = sum / 10 ;
int digit = sum % 10 ;
result.add( 0 , digit);
}
return result;
}
public static void main(String[] args) {
int [] arr1 = { 9 , 5 , 4 , 9 };
int [] arr2 = { 2 , 1 , 4 };
ArrayList<Integer> result = addArrays(arr1, arr2);
for ( int num : result) {
System.out.print(num);
}
System.out.println();
}
}
|
Python
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
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)
{
List< int > result = new List< int >();
int carry = 0;
for ( int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--)
{
int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
carry = sum / 10;
int digit = sum % 10;
result.Insert(0, digit);
}
return result;
}
static void Main()
{
int [] arr1 = { 9, 5, 4, 9 };
int [] arr2 = { 2, 1, 4 };
int n = arr1.Length;
int m = arr2.Length;
List< int > result = AddArrays(arr1, arr2, n, m);
foreach ( int digit in result)
{
Console.Write(digit);
}
Console.WriteLine();
}
}
|
Javascript
function addArrays(arr1, arr2) {
const result = [];
let carry = 0;
const n = arr1.length;
const m = arr2.length;
for (let i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
const sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
carry = Math.floor(sum / 10);
const digit = sum % 10;
result.unshift(digit);
}
return result;
}
const arr1 = [9, 5, 4, 9];
const arr2 = [2, 1, 4];
const result = addArrays(arr1, arr2);
console.log(result.join( '' ));
|
Time Complexity: O(max(n, m))
Auxiliary Space: O(max(n, m))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...