在给定约束条件下添加给定数组的元素?


对于这个问题,为了添加两个给定数组的元素,我们有一些约束条件,根据这些约束条件,添加的值将发生变化。两个给定数组 a[] 和 b[] 的和存储到第三个数组 c[] 中,以使它们将元素的和表示为个位数。如果和的位数大于 1,则第三个数组将将其拆分为两个个位数的元素。例如,如果和为 27,则第三个数组将存储为 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

解释

输出数组并从两个数组的第 0 个索引运行循环。对于循环的每次迭代,我们考虑两个数组中的下一个元素并将其相加。如果和大于 9,我们将和的各个数字推送到输出数组,否则我们将和本身推送到输出数组。最后,我们将较大输入数组的剩余元素推送到输出数组。

示例

#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;
}

更新于:2019年8月19日

205 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告