โจทย์
Add up the digits of n. If the result has more than one digit, add up its digits again. Repeat until a single digit remains.
Implement digital_root(n).
Input
n: A positive integer.
Output
Return the final single digit.
เงื่อนไข
1 ≤ n ≤ 10¹⁸
ตัวอย่าง
อินพุต:
n = 999
ผลลัพธ์ที่คาดหวัง:
expected = 9
อินพุต:
long long n = 999;
ผลลัพธ์ที่คาดหวัง:
long long expected = 9;
อินพุต:
long n = 999;
ผลลัพธ์ที่คาดหวัง:
long expected = 9;
คำอธิบาย
9 + 9 + 9 = 27, then 2 + 7 = 9.
อินพุต:
n = 38
ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
long long n = 38;
ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
long n = 38;
ผลลัพธ์ที่คาดหวัง:
long expected = 2;
คำอธิบาย
3 + 8 = 11, then 1 + 1 = 2.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Adding digits repeatedly eventually collapses the number to one digit.
คำใบ้ 2
You can simulate the repeated summing process until the value is less than 10.
คำใบ้ 3
Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.
ความซับซ้อนที่คาดหวัง
O(d log n) time, O(1) extra space