给定一个非负整数num,重复累加num中的每一个数字直至结果为个位数
Input:38
Output: 2 Explanation: The process is like:3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it
进阶:
不用循环或者递归,并且时间复杂度为O(1)
1:不停循环累加,直至结果小于10
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while num>9:
newNum = 0
for i in str(num):
newNum += int(i)
num = newNum
return num
2:(13)%9=(1*10+3)%9=(1*9+1+3)%9=(1+3)%9 故:(ab)%9=(a+b)%9(参考他人代码)
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num == 0:
return 0
else:
return (num - 1) % 9 + 1
算法题来自:https://leetcode-cn.com/problems/add-digits/description/