สำหรับปัญหานี้ การบวกสมาชิกของอาร์เรย์ 2 ชุดที่กำหนด มีเงื่อนไขที่ทำให้ค่าผลบวกเปลี่ยนไป ผลรวมของอาร์เรย์ a[] และ b[] จะเก็บในอาร์เรย์ c[] โดยให้ผลรวมของแต่ละคู่เป็นหลักเดียว หากผลรวมมีหลักมากกว่า 1 ให้แยกเป็นหลักเดี่ยวๆ ตัวอย่าง ผลรวมเป็น 27 จะเก็บเป็น 2, 7 ในอาร์เรย์ c[]
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;
}