ตัวเลขที่เก็บในอาร์เรย์: แต่ละหลักเก็บในสมาชิกแต่ละตัว ความยาวอาร์เรย์ = จำนวนหลัก ตัวอย่าง: 351932 → {3,5,1,9,3,2} (สมาชิกสุดท้าย = หลักหน่วย, สมาชิกแรก = หลักสำคัญที่สุด)
การบวก 1: บวกที่สมาชิกสุดท้าย ถ้าเป็น 9 จะมี carry ทำให้กลายเป็น 0 และบวก 1 ไปยังสมาชิกก่อนหน้า ต่อไปจนไม่มี carry
ตัวอย่าง: {3,5,7,9} + 1 = {3,5,8,0} (มี carry จาก 9 ทำให้ 7→8)
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
void addone(vector<int> &a) {
int n = a.size();
a[n-1] += 1;
int carry = a[n-1]/10;
a[n-1] = a[n-1] % 10;
for (int i = n-2; i >= 0; i--) {
if (carry == 1) {
a[i] += 1;
carry = a[i]/10;
a[i] = a[i] % 10;
}
}
if (carry == 1) a.insert(a.begin(), 1);
}
int main() {
vector<int> num{2, 3, 9, 9};
cout<<"The original number is : ";
for (int i = 0; i < num.size(); i++) cout << num[i];
cout<<endl;
addone(num);
cout<<"The incremented value is : ";
for (int i = 0; i < num.size(); i++) cout << num[i];
return 0;
}
ผลลัพธ์
The original number is 2399 The incremented value is 2400