Math Fundamentals18 sections · 814 units
Open in Course

Add Digits - Implementation

In pseudocode

Here's the mathematical solution:


function addDigits(n)
    if n = 0 then
        return 0
    return 1 + ((n - 1) mod 9)

For n=38n = 38: (381)mod9=37mod9=1(38 - 1) \bmod 9 = 37 \bmod 9 = 1, so the answer is 1+1=21 + 1 = 2. This matches the loop result but finishes in constant time.