digitalRoot
The digital root of a non-negative integer is the single-digit value obtained by an iterative process of summing digits, on each step using the result from the previous step as input to the next, until a single-digit number is reached. For example, the digital root of 123 is 1+2+3=6.
Examples
digitalRoot(123) → 6
digitalRoot(99) → 9
digitalRoot(493193) → 2
Starter code
function digitalRoot(n) {
}
Complexity of the optimal solution
Time O(1), space O(1). This solution uses a mathematical trick based on modular arithmetic to find the digital root in a single step. This is a highly efficient constant time operation.