보통 1명 해결 정답률 50.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

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 KKKaneki Ken Python 1,133 ms - 2/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 1개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.