Add the elements of given arrays with given constraints?

CServer Side ProgrammingProgramming

For this problem, to add elements of two given arrays we have some constraints based on which the added value will get changed. the sum of two given arrays a[] & b[] is stored into to third array c[]in such a way that they gave the some of the elements in single digit. and if the number of digits of the sum is greater than 1, then the element of the third array will split into two single-digit elements. For example, if the sum occurs to be 27, the third array with store it as 2,7.

Input: a[] = {1, 2, 3, 7, 9, 6}
       b[] = {34, 11, 4, 7, 8, 7, 6, 99}
Output: 3 5 1 3 7 1 4 1 7 1 3 6 9 9

Explanation

Output array and run a loop from the 0th index of both arrays. For each iteration of the loop, we consider the next elements in both arrays and add them. If the sum is greater than 9, we push the individual digits of the sum to output array else we push the sum itself. Finally, we push the remaining elements of the larger input array to the output array.

Example

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void split(int n, vector<int> &c) {
   vector<int> temp;
   while (n) {
      temp.push_back(n%10);
      n = n/10;
   }
   c.insert(c.end(), temp.rbegin(), temp.rend());
}
void addArrays(int a[], int b[], int m, int n) {
   vector<int> out;
   int i = 0;
   while (i < m && i < n) {
      int sum = a[i] + b[i];
      if (sum < 10) {
         out.push_back(sum);
      } else {
         split(sum, out);
      }
      i++;
   }
   while (i < m) {
      split(a[i++], out);
   }
   while (i < n) {
      split(b[i++], out);
   }
   for (int x : out)
   cout << x << " ";
}
int main() {
   int a[] = {1, 2, 3, 7, 9, 6};
   int b[] = {34, 11, 4, 7, 8, 7, 6, 99};
   int m =6;
   int n = 8;
   addArrays(a, b, m, n);
   return 0;
}
raja
Published on 19-Aug-2019 12:23:20
Advertisements