Add elements of two arrays into a new array

Given two arrays of positive integers, add their elements into a new array. The solution should add elements of both arrays one by one starting from 0’th index and split the sum into individual digits if it’s a two-digit number.


 

For example,


Input:
a = { 23, 5, 2, 7, 87 }
b = { 4, 67, 2, 8 }

Output: { 2, 7, 7, 2, 4, 1, 5, 8, 7 }

 
Input:
a = {}
b = { 4, 67, 2, 8 }

Output: { 4, 6, 7, 2, 8 }

 

The idea is run a loop where we consider every pair of elements present at same index in both arrays and add them. Now if the sum is two-digit number, we add its individual digits to the result array else we add the single-digit sum to the result array. Finally we add the remaining elements of larger array to the result array.

C++

Download   Run Code

Output:

2 7 7 2 4 1 5 8 7


 

Here is another solution which construct a string containing the result by appending sum of each pair of elements to it and finally add each character to vector of integers.

C++

Download   Run Code

Output:

4 6 7 2 8

 
The time complexity of both solutions is O(m + n) where m is the size of first vector and n is the size of second vector.

 
Author: Aditya Goel

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz