Medium 0 solved 0% acceptance

Digital Root

Sum the digits repeatedly until one digit remains.

What you'll learn

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

Problem

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.

Constraints

1 ≤ n ≤ 10¹⁸

Examples

Example 1
Input:
n = 999

Expected output:
expected = 9
Input:
long long n = 999;

Expected output:
long long expected = 9;
Input:
long n = 999;

Expected output:
long expected = 9;

Explanation

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

Example 2
Input:
n = 38

Expected output:
expected = 2
Input:
long long n = 38;

Expected output:
long long expected = 2;
Input:
long n = 38;

Expected output:
long expected = 2;

Explanation

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

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Adding digits repeatedly eventually collapses the number to one digit.

Hint 2

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

Hint 3

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

Expected complexity

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

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.