หาผลรวมหลักเลขของตัวเลขจนกว่าผลรวมจะกลายเป็นหลักเดียว (Single Digit)
ตัวอย่าง: 14520 → 1+4+5+2+0 = 12 → 1+2 = 3 (คำตอบ)
หลักการ: ผลรวมหลักเลขของตัวเลขที่หาร 9 ลงตัว = 9 เสมอ ตัวเลขอื่นหาร 9 取餘數 = ผลรวมสุดท้าย
ตัวอย่างโค้ด
#include<bits/stdc++.h>
using namespace std;
int sum_digits(int n) {
if (n == 0) return 0;
else if (n % 9 == 0) return 9;
else return (n % 9);
}
int main() {
int x = 14520;
cout<<sum_digits(x)<<endl;
return 0;
}
ผลลัพธ์
3