Share the joy
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Solution. We need to refer to this wiki digital root. Basically, the result is num mod 9. But we need to exclude 2 exceptions:
1. When num is 0, we need to return 0.
2. When mod is 0, we need to return 0.
In this way, easiest one should beĀ
check my code on github: link