258. Add Digits

The result slides repeatedly from 1 to 9, and when <num> is able to be rounded by 9, the result is <9> (e.g. input 36, 45, 54...). Thus, we can get the result by calculating the remainder of the division by 9.

Special case: the output could be 0 only if the input is 0.

#python solution

class Solution:
    def addDigits(self, num: int) -> int:
        res = num % 9
        if res == 0:
            if num == 0:
                return 0
            else:
                return 9
        else:
            return res

Last updated

Was this helpful?