leetcode 258. Add Digits ( Python )

398 阅读21分钟

描述

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
Since 2 has only one digit, return it.

解析

根据题意,把每位数字进行相加,最后一直加到得到一个十以内的数字即可,时间复杂度为 O(1),空间复杂度为 O(1),因为整数的位数最多 32 位。

解答

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        tmp = 0
        for i in str(num):
            tmp += int(i)
        if tmp<10:
            return tmp
        else:
            return self.addDigits(tmp)
                
                 	      
		

运行结果

Runtime: 20 ms, faster than 68.96% of Python online submissions for Add Digits.
Memory Usage: 11.7 MB, less than 86.34% of Python online submissions for Add Digits.

解析

根据题意,还可以找出一定的规律

// 前一位是数字,后一位是位数累加和的结果
(1 1),(2 2),(3 3),(4 4),(5 5),(6 6),(7 7),(8 8),(9 9),(10 1),(11 2),(12 3),(13 4),(14 5),(15 6),(16 7),(17 8),(18 9),(19 1),(20 2),(21 3),(22 4),(23 5),(24 6),(25 7),(26 8),(27 9),(28 1)...

可以发现累加和是按照 1~9 的顺序周而复始地出现,时间复杂度为 O(1),空间复杂度为 O(1)。

解答

class Solution(object):
def addDigits(self, num):
    """
    :type num: int
    :rtype: int
    """
    return 0 if num==0 else (num-1)%9+1
              
                 	      
		

运行结果

Runtime: 12 ms, faster than 96.72% of Python online submissions for Add Digits.
Memory Usage: 11.8 MB, less than 46.58% of Python online submissions for Add Digits.

每日格言:生命不等于是呼吸,生命是活动。

请作者喝吃泡芙 支付宝

支付宝

微信

微信