在給定約束條件下新增給定陣列的元素?
對於這個問題,為了新增兩個給定陣列的元素,我們有一些約束條件,根據這些約束條件,新增的值將發生變化。兩個給定陣列 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; }
廣告