视频分析:
http://v.youku.com/v_show/id_XMTMzMjUwNjk3Mg==.html
题干:
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?
代码:
from math import *
class Solution(object):
def sumdig(self,num):
re=0
tmp=num
while True:
re+=tmp%10
tmp=tmp//10
if tmp<=0:
break
return re
def addDigits2(self, num):
"""
:type num: int
:rtype: int
"""
tmp=num
while True:
if tmp<10 and tmp>=0:
return tmp
else:
tmp=self.sumdig(tmp)
def addDigits(self, num):
return int(num-9*floor((num-1)/9))