Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

บวกอาร์เรย์สองตัวด้วยเงื่อนไขพิเศษ ในภาษา C

บวกอาร์เรย์ arr1 และ arr2 ตาม index:

  • บวกค่าที่ index เดียวกัน
  • ถ้าผลรวม ≥ 10 (หลายหลัก) → แยกหลักแต่ละหลักใส่ output
  • ส่วนที่เหลือของอาร์เรย์ที่ยาวกว่า → copy ต่อท้าย (แยกหลักถ้าจำเป็น)

ตัวอย่าง

arr1 = {9323, 8, 6, 55, 25, 6}

arr2 = {38, 11, 4, 7, 8, 7, 6, 99}

Output: 9 3 6 1 1 9 1 0 6 2 3 3 1 3 6 9 9

โค้ดตัวอย่าง (C++)

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

void splitDigits(int num, vector<int> &out) {
    vector<int> digits;
    while (num) { digits.insert(digits.begin(), num%10); num/=10; }
    out.insert(out.end(), digits.begin(), digits.end());
}

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 splitDigits(sum, out);
        i++;
    }
    while (i < m) splitDigits(a[i++], out);
    while (i < n) splitDigits(b[i++], out);
    for (int x: out) cout << x << " ";
}

int main() {
    int a[] = {9323, 8, 6, 55, 25, 6};
    int b[] = {38, 11, 4, 7, 8, 7, 6, 99};
    addArrays(a, b, 6, 8);
    return 0;
}

ผลลัพธ์

9 3 6 1 1 9 1 0 6 2 3 3 1 3 6 9 9