1. 程式人生 > >【leetcode】【數論】258.Add Digit (python)

【leetcode】【數論】258.Add Digit (python)

題目描述 Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 給定一個非負整數,重複將其每位數相加,直到結果只有一位數為止。

思路一 採用最簡單的迴圈計算方法,但是這樣不符合題目要求。

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while True:
m = 0 while num > 0: m += num % 10 num //= 10 if m < 10: return m if m >= 10: num = m

思路二 觀察規律,1,2,3…9的數根分別為1,2,3…9。10,11,12…18的數根也分別為1,2,3…9。由規律我們可以得到: 當n = 0時,res = 0; 當n > 0時,res = 1+(n-1) mod 9

程式碼

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