按照给定的约束添加给定数组中的元素?


这里解决一个问题。我们将两个数组的元素相加并存储在另一个数组中。不过,我们要遵循一些约束条件。这些约束条件如下所示 −

  • 两个数组的第 0 个索引开始进行相加
  • 如果和大于一位数,则将和拆分,并将每位数字放置在相应的位置
  • 较大输入数组的剩余数字将存储在输出数组中

让我们看看算法以了解思路。

算法

addArrayConstraints(arr1, arr2)

Begin
   define empty vector out
   i := 0
   while i is less than both arr1.length and arr2.length, do
      add := arr1[i] + arr2[i]
      if add is single digit number, then
         insert add into out
      else
         split the digits and push each digit into out
   end if
done
while arr1 is not exhausted, do
   insert each element directly into out if they are single digit, otherwise split and insert
done
while arr2 is not exhausted, do
   insert each element directly into out if they are single digit, otherwise split and insert
done
End

示例

#include<iostream>
#include<vector>
using namespace std;
void splitDigit(int num, vector<int> &out) { //split the digits and store into vector to add into array
   vector<int> arr;
   while (num) {
      arr.insert(arr.begin(), num%10);
      num = num/10;
   }
   out.insert(out.end(), arr.begin(), arr.end());
}
void addArrayConstraints(int arr1[], int arr2[], int m, int n) {
   vector<int> out;
   int i = 0; //point current index of arr1 and arr2
   while (i < m && i <n) {
      int add = arr1[i] + arr2[i];
      if (add < 10) //if it is single digit, put the sum, otherwise split them
         out.push_back(add);
      else
         splitDigit(add, out);
      i++;
   }
}
while (i < m) //if arr1 has more elements
   splitDigit(arr1[i++], out);
while (i < n) //if arr2 has more elements
   splitDigit(arr2[i++], out);
for (int i = 0; i< out.size(); i++)
   cout << out[i] << " ";
}
main() {
   int arr1[] = {9323, 8, 6, 55, 25, 6};
   int arr2[] = {38, 11, 4, 7, 8, 7, 6, 99};
   int n1 = sizeof(arr1) / sizeof(arr1[0]);
   int n2 = sizeof(arr2) / sizeof(arr2[0]);
   addArrayConstraints(arr1, arr2, n1, n2);
}

输出

9 3 6 1 1 9 1 0 6 2 3 3 1 3 6 9 9

更新于: 2020 年 7 月 2 日

99 次浏览

开启美好职业生涯

完成课程,获得认证

立即开始
广告