The one-digit oracle
- O(log n) · Easy
- Free
- Python
- JavaScript
- digits
- loops
Problem
The tower of Ormund has no lock on its door. A stone oracle guards it instead, and the oracle only understands single digits. When a traveler speaks a number, the oracle adds up its digits; if the result has more than one digit, it adds up the digits of that result, and it keeps going until only one is left. That digit opens the door.
Write a function that takes a whole number, 0 or greater, and returns that final digit as a whole number. With 4783: 4 + 7 + 8 + 3 = 22, which has two digits; 2 + 2 = 4, which has one. You return 4.
A number that already has a single digit stays as it is: 7 returns 7, and 0 returns 0.
Examples
A single round
16 → 7
Two rounds
942 → 6
Two rounds, from two digits
38 → 2
Already one digit
7 → 7
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def digital_root(n):
passJavaScript
function digitalRoot(n) {
}It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.