LeetCode-258. Add Digits

发布于 2017-07-13 02:36:20

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

For example:

Given num = 38, 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?



这个题目解释了那么多都是迷惑人的,然后还要不使用循环和递归,其实写个递归一看就能看出来规律,这个其实就是取9的余数,当输入是0的时候返回0,当能整除的时候,返回上一个数的余数加1就可以了。

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