添加具有给定约束的给定数组的元素?
在这里,我们将看到一个问题。我们将添加两个数组元素并将它们存储到另一个数组中。但是我们将遵循一些约束条件。这些约束如下-
应该从两个数组的第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