leetcode with python:258. Add Digits

题目:

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

给定一数,将其每一位数字相加,得出结果后重複,直到结果是个位数回传
ex:input:38=>output:2
explanation:
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2

这题我用最直观的方法去做

class Solution:    def addDigits(self, num: int) -> int:        while num>=10:            ans=0            while num!=0:                ans=ans+num%10                num=num//10            num=ans        return num

我真的将每一位数相加,不断重複,直到< 10
但这样解时间也不算太慢
最后执行时间30ms(faster than 96.83%)

而在看过讨论区后,才发现是有规则可循的
有人证出该数除9的余数即为此题的解答
而整除的话答案就是9(除非是0)

class Solution:    def addDigits(self, num: int) -> int:        ans=num%9        if ans==0 and num!=0:            return 9         return ans

所以我们只要算出该数除9的余数
再对一些特例做处理答案就到手了
最后执行时间24ms(faster than 99.78%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章