ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Digital Root

Sum the digits repeatedly until one digit remains.

สิ่งที่คุณจะได้เรียนรู้

  • Sum digits repeatedly until one digit remains
  • Combine an inner loop with an outer stopping condition
  • Spot the shortcut formula with modulo 9

โจทย์

ดูฉบับแปล

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¹⁸

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

ตัวอย่างที่ 2
อินพุต:
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

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก