题目:
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?
题意:
给定一个非负整数,重复地将这个数的各个数字相加,直到结果是一个数字。返回这个数字。
代码:
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num < 10 :
return num
else :
temp = 0;
while num/10 > 0 :
temp = temp + num%10;
num = num/10 ;
return self.addDigits(temp + num ) ;
网上其他代码:
if num < 10 :
return num
return (num - 1) % 9 + 1
或:
if(num < 10) :
return num;
else :
return self.addDigits(num / 10 + num % 10);