การเก็บตัวเลขในอาร์เรย์
ตัวเลขแต่ละหลักเก็บในแต่ละอิลิเมนต์ของอาร์เรย์ เช่น 234 → {2, 3, 4}
ตัวอย่าง
a = {2, 9, 6} (หมายถึง 296)
b = {6, 3, 8} (หมายถึง 638)
ผลลัพธ์: 934คำนวณ: 6+8=14 (เก็บ 4 ส่ง carry 1) → 9+3+1=13 (เก็บ 3 ส่ง carry 1) → 2+6+1=9
อัลกอริทึม
- ตรวจสอบว่าอาร์เรย์ไหนยาวกว่า
- บวกจากหลักหน่วย (index สุดท้าย) ไปยังหลักมากที่สุด
- เก็บ carry ไปรอบถัดไป
- ถ้าอาร์เรย์หนึ่งหมด ให้บวกอาร์เรย์ที่เหลือพร้อม carry
- เก็บผลลัพธ์ในอาร์เรย์ sum แล้วพิมพ์
โค้ดภาษา C++
#include <iostream>
using namespace std;
int Sum(int a[], int b[], int n, int m) {
int sum[n];
int i = n - 1, j = m - 1, k = n - 1;
int c = 0, s = 0;
while (j >= 0) {
s = a[i] + b[j] + c;
sum[k] = (s % 10);
c = s / 10;
k--; i--; j--;
}
while (i >= 0) {
s = a[i] + c;
sum[k] = (s % 10);
c = s / 10;
i--; k--;
}
for (int i = 0; i <= n-1; i++)
cout << sum[i];
return 0;
}
int main() {
int a[] = {5, 6, 9};
int b[] = {3, 8};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
cout << "The sum is ";
if (n >= m) Sum(a, b, n, m);
else Sum(b, a, m, n);
return 0;
}ผลลัพธ์
The sum is 607