DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
rafaacioly profile image
Rafael Acioly

why 1 + (n - 1)?

Collapse
j_mplourde profile image
Jean-Michel Plourde

I tested it with just n and it works fine.

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