LeetCode 258 Add Digits (Python)

Posted by 小明MaxMing on July 26, 2020

题目

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

解题思路

可以通过找规律或者数学证明来得到O(1)的方法,基本过程请看视频

代码

class Solution:
    def addDigits(self, num: int) -> int:
        if num <= 9:
            return num
        tmp = 0
        while num > 0:
            tmp += num % 10
            num //= 10
        return self.addDigits(tmp)
class Solution:
    def addDigits(self, num: int) -> int:
        return (num - 1) % 9 + 1 if num else 0

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅