【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

猜你喜欢

转载自blog.csdn.net/qq_42011358/article/details/83472988