2 lines Python with explanation


  • 0
    A
    class Solution(object):
        def addDigits(self, num):
            if num==0: return 0
            return 1 + (num-1)%9
    

    Explanation (from Wolfram Alpha):

    The digital root dr(n) of an integer n can be computed without actually performing the iteration using the simple congruence formula:

    Congruence formula

    = 1 + [n-1(mod 9)]


Log in to reply
 

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