Add Digits (Digit root)

题目描述

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?

解题方法

brute force

将每个数字加起来,放到stack里,然后进行跟题目一样的运算

找规律

0       0
1       1
2       2
3       3
...
10     1
11     2
12     3
...
17     8
18     9

可以看出其实是不断重复有规律的,0是0,9的倍数是9,其余就是% 9

Solution

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