qianlei90 / Blog

那些该死的文字呦
https://qianlei.notion.site
103 stars 20 forks source link

258. Add Digits #22

Open qianlei90 opened 7 years ago

qianlei90 commented 7 years ago

258. Add Digits

Tags: 印象笔记

[toc]


Question

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.

hint

A naive implementation of the above process is trivial. Could you come up with other methods?

follow up

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

Solution 1

按照定义来写就能算出来. 先把数字转成字符串, 然后对每一位相加,重复执行.

Show me the code

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        def calculate(n):
            if len(str(n)) <= 1:
                return n
            return calculate(reduce(lambda x, y: int(x) + int(y), str(n)))

        return calculate(num)

Solution 2

n进制数abc...
= a * n^m + b * n^(m-1) + c * n^(m-2) + ...
= a * (n^m - 1) + b * (n^(m - 1) - 1) + c * (n^(m-2) - 1) + ... + (a +b +c + ...)
= a * (n - 1) * (...) + b * (n - 1) * (...) + c * (n - 1) * (...) + ... + (a + b + c + ...)
= (...) * (n - 1) + ... + (a +b +c + ...)

所以对于10进制数来说, root(x) = y * 9 +r, 即 root(x) = x % 9. 再考虑题目中的非负, 还有可能出现0, root(0) = 0

Show me the code 1

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

Show me the code 2

对上面的代码简化为1行:

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

- 完 -