目录/Table of Content
第二十六天问:Add Digits
这次题目很简单:给你一个整数,你需要做的只是把它所有的数字相加,一直重复直到只有个位数。而我们现在就是要求这个个位数是多少。
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目&示例 (引用自 LeetCode)
Given a non-negative integer
num
, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: 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 1 1) runtime?
解题思路
简单解法:把数字换成字符串,然后把这「字符串」的数字一个个的换回数字格式相加,直到只剩一个数字为止。时间复杂度为 O( log n \log n logn), n n n是数字的长度。
代码一 (简单解法)
时间复杂度:O(
log
n
\log n
logn)
空间复杂度:O(
1
1
1)
class Solution:
def addDigits(self, num: int) -> int:
while num >= 10:
num = str(num)
res = 0
for i in num:
res += int(i)
num = res
return num
另一个解法,就必须考虑这题目的数学含意。利用这题的数学规律就可以用一句就搞定这题目。我把原文答案链结放在这里,有兴趣的可以参考。
代码二 (数学解法)
时间复杂度:O(
1
1
1)
空间复杂度:O(
1
1
1)
class Solution:
def addDigits(self, num: int) -> int:
return 1 + (num - 1) % 9 if num else 0