
对于这个问题,要添加两个给定数组的元素,我们有一些约束,基于这些约束,添加的值将发生变化。两个给定数组 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号