Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, 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) runtime?
思路:
- 利用/和%运算可以得到num的每个数字,把各个数字的和加起来,如果比9大,继续使用该方法运算,直至各个数字的和小于9。但是好像不满足不使用loop的要求。
- 把数字用字符串表示,得到sum。
- 其他人的思路:abcde = 10000a + 1000b + 100c + 10d + e = (a + b + c + d + e) + 9999a + 999b +99c + 9d。所以用9去mod就行。如果结果是9,mod一下就变成0了,这道题里又不可能结果是0,所以mod前-1然后mod完+1就行
#!usr/bin/env
# -*-coding:utf-8 -*-
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num <=9:
return num
sum = 0
while(num):
sum += num%10
num= num/10
return self.addDigits(sum)
def addDigits2(self, num):
return (num-1)%9 + 1
if __name__ == '__main__':
sol = Solution()
print sol.addDigits(38)
print sol.addDigits(138)
print sol.addDigits2(38)