258. Add Digits
Problem
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?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
本质是数学问题,数根: 一个数的数根(digital root)就是它对9的余数
数根就是不断地求这个数的各位数之和,直到求到个位数为止。所以数根一定和该数模9同余 ,但是数根又是大于零小于10的,所以数根模9的余数就是它本身,也就是说该数模9之后余数就是数根。 特殊情况是数根是9的时候,这时候余数是0
12345 = 1 * 9999 + 2 * 999 + 3 * 99 + 4 * 9 + 5 + (1+ 2+ 3 + 4)
solution
class Solution(object):
def addDigits(self, num):
return num if num == 0 else num % 9 or 9
使用递归,时间复杂度高于题目要求
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
j = 0
if num < 10:
return num
for i in str(num):
j += int(i)
return self.addDigits(j)

浙公网安备 33010602011771号