1 line O(1) Python Solution (based on hint)


  • 5
    S

    Use modulus operator to determine digital root. Subtract by one first and then add 1 at the end so that the digital root of 9 (8+1) is correct instead of (9 % 9 == 0). Check for the 0 case.

    class Solution(object):
            def addDigits(self, num):
                return 0 if not num else 1 + (num - 1) % 9

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.