Here's the mathematical solution:
function addDigits(n)
if n = 0 then
return 0
return 1 + ((n - 1) mod 9)
For : , so the answer is . This matches the loop result but finishes in constant time.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
In pseudocode
Here's the mathematical solution:
function addDigits(n)
if n = 0 then
return 0
return 1 + ((n - 1) mod 9)
For : , so the answer is . This matches the loop result but finishes in constant time.