258. Add Digits

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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while True:
            n = 0
            for i in str(num):
                n += int(i)
            if n<10 and n>=0:
                return n
            num = n

O(1) solution:

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

没啥意思,找规律的题。

posted @ 2018-10-05 11:11  bernieloveslife  阅读(89)  评论(0)    收藏  举报