Add Arrays - C++ Solution

1. Introduction

In this post, we will tackle a unique problem in array manipulation using C++: adding elements of two arrays and splitting two-digit sums into individual digits. This problem exemplifies the use of basic array operations and digit manipulation in programming.

Problem

Given two arrays of positive integers, we need to add their elements into a new array. The addition should be done one by one starting from the 0'th index, and any two-digit sum must be split into individual digits.

Examples:

- Input: [23, 5, 2, 7, 87], [4, 67, 2, 8]

Output: [2, 7, 7, 2, 4, 1, 5, 8, 7]

- Input: [], [4, 67, 2, 8]

Output: [4, 6, 7, 2, 8]

2. Solution Steps

1. Iterate over the two arrays simultaneously, handling uneven lengths.

2. For each pair of elements, add them and check if the sum is a two-digit number.

3. If the sum is a single digit, add it directly to the result array.

4. If the sum is two digits, split it and add the individual digits to the result array.

5. Return the resulting array.

3. Code Program

#include <iostream>
#include <vector>
using namespace std;

// Function to split a two-digit number into individual digits
void addDigits(vector<int>& result, int number) {
    if (number >= 10) {
        result.push_back(number / 10);
        result.push_back(number % 10);
    } else {
        result.push_back(number);
    }
}

// Function to add two arrays
vector<int> addArrays(vector<int>& arr1, vector<int>& arr2) {
    vector<int> result;
    int i = 0, j = 0;

    while (i < arr1.size() || j < arr2.size()) {
        int sum = 0;
        if (i < arr1.size()) sum += arr1[i++];
        if (j < arr2.size()) sum += arr2[j++];
        addDigits(result, sum);
    }

    return result;
}

int main() {
    vector<int> arr1 = {23, 5, 2, 7, 87};
    vector<int> arr2 = {4, 67, 2, 8};
    vector<int> result = addArrays(arr1, arr2);

    for (int num : result) {
        cout << num << " ";
    }
    return 0;
}

Output:

2 7 7 2 4 1 5 8 7

Explanation:

The addArrays function iterates over both arrays, adding corresponding elements. The addDigits function is used to split two-digit sums into individual digits before adding them to the result array. This approach ensures that all elements are processed, and any two-digit sums are appropriately handled, as demonstrated by the output for the given examples.


Comments