Skip to content
BytePatterns

Repeated Digit Sum

EasyMath & Number Theory#modular-arithmetic#math~15m

Problem

Take a non-negative whole number and add up its decimal digits. If the result has more than one digit, add up its digits again, and keep going until a single digit remains. Return that digit, ideally without looping at all.

Examples

Input:  n = 38
Output: 2
Why:    3 + 8 = 11, then 1 + 1 = 2
Input:  n = 99999
Output: 9
Why:    the digits add to 45, and 4 + 5 = 9
Input:  n = 0
Output: 0
Why:    edge case, zero is already one digit and the only number that ends at 0

Hints

0 / 3

Stuck on the idea rather than the code? Modular Arithmetic covers it.