Q:
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?
A:
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ num_str = str(num) numbers = list(num_str) sum_num = sum(int(t) for t in numbers) if sum_num < 10: return sum_num else: # print sum_num return self.addDigits(sum_num)
改进以后:
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ if num == 0: return 0 else: return (num-1)%9+1