Given a constraint, add the elements of the given array

PHPz
Release: 2023-09-05 13:01:06
forward
1019 people have browsed it

Given a constraint, add the elements of the given array

For this problem, to add elements of two given arrays, we have some constraints, based on these constraints, the added values will change. The sum of two given arrays a[] and b[] is stored into a third array c[] so that they give some elements in unit numbers. If the number of digits in the sum is greater than 1, the elements of the third array are split into two single-digit elements. For example, if the sum is 27, the third array will store it as 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
Copy after login

Description

Output arrays and run a loop from the 0th index of both arrays. For each iteration of the loop, we consider the next elements in both arrays and add them. If the sum is greater than 9, we push the individual numbers of the sum to the output array, otherwise we push the sum itself to the output array. Finally, we push the remaining elements of the larger input array to the output array.

Example

#include  #include using namespace std; void split(int n, vector &c) { vector 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 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; }
Copy after login

The above is the detailed content of Given a constraint, add the elements of the given array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!