首頁  >  文章  >  後端開發  >  給定約束條件,將給定數組的元素相加

給定約束條件,將給定數組的元素相加

PHPz
PHPz轉載
2023-09-05 13:01:061057瀏覽

給定約束條件,將給定數組的元素相加

對於這個問題,要新增兩個給定陣列的元素,我們有一些約束,基於這些約束,新增的值將會改變。兩個給定數組 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;
}
#

以上是給定約束條件,將給定數組的元素相加的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除