Trung bình 0 đã giải Tỷ lệ chấp nhận 0%

Digital Root

Sum the digits repeatedly until one digit remains.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ n ≤ 10¹⁸

Ví dụ

Ví dụ 1
Đầu vào:
n = 999

Kết quả mong đợi:
expected = 9
Đầu vào:
long long n = 999;

Kết quả mong đợi:
long long expected = 9;
Đầu vào:
long n = 999;

Kết quả mong đợi:
long expected = 9;

Giải thích

9 + 9 + 9 = 27, then 2 + 7 = 9.

Ví dụ 2
Đầu vào:
n = 38

Kết quả mong đợi:
expected = 2
Đầu vào:
long long n = 38;

Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long n = 38;

Kết quả mong đợi:
long expected = 2;

Giải thích

3 + 8 = 11, then 1 + 1 = 2.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Adding digits repeatedly eventually collapses the number to one digit.

Gợi ý 2

You can simulate the repeated summing process until the value is less than 10.

Gợi ý 3

Watch out for very large inputs; the process is simple, but repeated passes over the digits are the main work.

Độ phức tạp mong đợi

O(d log n) time, O(1) extra space

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.