보통 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

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.