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.
思路:这个题方法有很多,大体思路是把数字转化为字符串,再分别转为数字相加,再转为字符串...其中判定结束的方法可以是数字小于10,也可以是数字长度等于1.
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
l = len(str(num))
if l == 1:
return num
sum = 0
for i in str(num):
sum += int(i)
return self.addDigits(sum)
当然也可以只靠数字计算
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while(num >= 10):
temp = 0
while(num > 0):
temp += num % 10
num /= 10
num = temp
return num
还有一种比较聪明的方法,因为
1 % 9 = 1
10 % 9 = 1
100 % 9 = 1
所以N % 9 = a[0] + a[1] + ..a[n](除了N%9=0的时候)
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