Python solution with detailed explanation


  • 1
    G

    Solution

    Add Digits https://leetcode.com/problems/add-digits/

    Recursive Solution (can be iterative as well)

    class Solution(object):
        def addDigits(self, num):
            """
            :type num: int
            :rtype: int
            """
            sum = 0
            while num:
                sum = sum + num%10
                num = num//10
            if sum > 9:
                return self.addDigits(sum)
            else:
                return sum
    

    Keep taking the mod with 9

    • Example: 534 = 500 + 40 + 3 = 5(99+1) + 4(9+1) + 4
    • 534%9 = 5+3+4 = 12
    • 12 = 1(9+1) + 2. 12%9 = 1+2
    class Solution(object):
        def addDigits(self, num):
            if num == 0:
                return 0
            while num > 9:
                num = num % 9
                if num == 0:
                    return 9
            return num
    

Log in to reply
 

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