InferenceAI

Enter at least two characters to search.

Start free

Repeated Digit Sum

easyMath15 min10 XP

Given a non-negative integer n, repeatedly replace it with the sum of its digits until it has a single digit, and return that digit.

Requirements

  • A loop is fine; the O(1)O(1) solution uses the fact that a number and its digit sum leave the same remainder modulo 9.

Constraints

  • 0≤n≤231−10 \le n \le 2^{31} - 1

Examples

EXAMPLE WALKTHROUGHtwo rounds

A guided view of the published example, not a trace of your code.

INPUT[38]
TASKrepeated_digit_sum()
EXPECTED OUTPUT2

Start with the input values shown in this example.

Example 1 of 3

Input: n = 38

Output: 2

Explanation: two rounds

Input: n = 0

Output: 0

Explanation: zero

Input: n = 9

Output: 9

Explanation: single digit

Hint 1

Write a helper that sums digits, and loop while n >= 10.

Hint 2

For n > 0 the answer is 1 + (n - 1) % 9.

Topics

DSAMathPython