DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
dry profile image
Hayden Mankin

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