按照給定的約束新增給定陣列中的元素?
這裡解決一個問題。我們將兩個陣列的元素相加並存儲在另一個數組中。不過,我們要遵循一些約束條件。這些約束條件如下所示 −
- 兩個陣列的第 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP