Home  >  Article  >  Backend Development  >  Given a constraint, add the elements of the given array

Given a constraint, add the elements of the given array

PHPz
PHPzforward
2023-09-05 13:01:061097browse

Given a constraint, add the elements of the given array

For this problem, to add elements of two given arrays, we have some constraints, based on these constraints, the added values ​​will change. The sum of two given arrays a[] and b[] is stored into a third array c[] so that they give some elements in unit numbers. If the number of digits in the sum is greater than 1, the elements of the third array are split into two single-digit elements. For example, if the sum is 27, the third array will 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

Description

Output arrays 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 numbers of the sum to the output array, otherwise we push the sum itself to the output array. 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;
}

The above is the detailed content of Given a constraint, add the elements of the given array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete