loading...

re: Daily Challenge #264 - Digital Root VIEW POST

FULL DISCUSSION
 

Python 3 using direct calculation. Defined as function with test cases in the tio link.

digital_root = lambda n: 0 if n == 0 else 1 + (n - 1) % 9

Try it online!

 
 

I tested it with just n and it works fine.

 

It's important to remember that the % operator happens before +, this solves the edge cases around numbers divisible by 9 without needing extra if statements/ternaries.

For instance,

18 -> 1 + 8 = 9

however,

18 % 9 = 0

which does not fit the problem specification, so instead we do

(18 - 1) % 9 + 1 = 17 % 9 + 1 = 8 + 1 = 9
code of conduct - report abuse