Problem
Given two arrays of positive integers, add their elements into a new array. You should add both arrays, one by one starting from the 0th index, and split the sum into individual digits if it is a multi-digit number.
Sample Input
[23, 5, 2, 7, 87] [4, 67, 2, 8]
Sample Output
[2, 7, 7, 2, 4, 1, 5, 8, 7]
Approach
The approach is to run a loop that takes into account all pairs of elements at the same index and add them into the resultant array. Note that if sum is a multi-digit number, then simply add its digits to the resultant array. At last, we add remaining values of the larger array into the resultant array. The time complexity of the approach is O(max(sizes of arrays)).
C++ Programming
#include <iostream>
#include <vector>
using namespace std;
void helper(int num, vector<int> &ans)
{
if (num)
{
helper(num/10, ans);
ans.push_back(num % 10);
}
}
void solve(vector<int> const &a, vector<int> const &b, vector<int> &ans)
{
int m = a.size(), n = b.size();
int i = 0;
while (i < m && i < n)
{
int sum = a[i] + b[i];
helper(sum, ans);
i++;
}
while (i < m) {
helper(a[i++], ans);
}
while (i < n) {
helper(b[i++], ans);
}
}
int main()
{
vector<int> a = { 2, 5, 2, 7, 55 };
vector<int> b = { 1, 7, 2, 9 };
vector<int> ans;
solve(a, b, ans);
for (int i: ans) {
cout << i << " ";
}
}
Output
3 1 2 4 1 6 5 5
Java Programming
import java.util.ArrayList;
import java.util.List;
class Main
{
public static void helper(int num, List<Integer> ans)
{
if (num > 0)
{
helper(num/10, ans);
ans.add(num % 10);
}
}
public static void solve(int[] a, int[] b, List<Integer> ans)
{
int m = a.length, n = b.length;
int i = 0;
while (i < m && i < n)
{
int sum = a[i] + b[i];
helper(sum, ans);
i++;
}
while (i < m) {
helper(a[i++], ans);
}
while (i < n) {
helper(b[i++], ans);
}
}
public static void main(String[] args)
{
int[] a = { 1, 5, 2, 7, 8 };
int[] b = { 1, 7, 2, 9 };
List<Integer> ans = new ArrayList<>();
solve(a, b, ans);
System.out.print(ans);
}
}
Output
[2, 1, 2, 4, 1, 6, 8]
Python
def helper(num, ans):
if num > 0:
helper(num // 10, ans)
ans.append(num % 10)
def solve(a, b, ans):
m = len(a)
n = len(b)
i = 0
while i < m and i < n:
sum = a[i] + b[i]
helper(sum, ans)
i = i + 1
while i < m:
helper(a[i], ans)
i = i + 1
while i < n:
helper(b[i], ans)
i = i + 1
a = [2, 1, 2, 11]
b = [5, 6, 2, 11]
ans = []
solve(a, b, ans)
print(ans)
Output
[7, 7, 4, 2, 2]
People are also reading:
Leave a Comment on this Post