Add Digits – Python 3 (Week 11 – 03)

Solution 1

class Solution:
    def addDigits(self, num: int) -> int:
        
        ans = num
        
        while num > 9:
            ans = 0
            while num > 0:
                ans += num % 10
                num = num // 10
            num = ans
            
        return ans

Solution 2

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

        return (num - 1) % 9 + 1
       

Time complexity: O(n), assume n is the # of digits in the input. Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started