KatInterview

Digital Root via Modular Arithmetic

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationmathmodular arithmeticnumber theory

Last updated

Tests understanding of modular arithmetic by computing the digital root of a large integer without repeatedly summing digits in a loop.

Digital Root of a Large Integer

The digital root of a non-negative integer is obtained by repeatedly replacing the number with the sum of its digits until a single digit (0–9) remains.

For example, starting with 9875:

  • 9 + 8 + 7 + 5 = 29
  • 2 + 9 = 11
  • 1 + 1 = 2

So the digital root of 9875 is 2.

There is a well-known closed-form formula that computes this in O(1) using modular arithmetic — your task is to implement it.

Given a non-negative integer n, return its digital root.

Note: Your solution must not use any digit-by-digit iteration or string conversion. It must use the modular arithmetic formula directly.

(For grading purposes, your function is judged on its return value only — the correct closed-form formula naturally satisfies the no-iteration requirement, and the hidden test cases will verify correctness.)

Constraints

  • 0 <= n <= 10^18
  • The function must return a single integer in the range [0, 9].
  • For n = 0, the digital root is 0.

Examples

Example 1

Input: digital_root(9875)

Output: 2

Example 2

Input: digital_root(0)

Output: 0

Example 3

Input: digital_root(18)

Output: 9

Hints

Hint 1

The digital root of any positive integer n equals 1 + ((n − 1) mod 9). Think about why numbers cycle through 1–9 repeatedly under digit-sum reduction.

Hint 2

The only special case is n = 0, which should return 0 rather than 9.

Hint 3

This formula works because the digit sum of n has the same remainder mod 9 as n itself — so repeated digit-summing always converges to the value n mod 9 (adjusted so the result is never 0 for positive n).