Python3解leetcode Binary Tree PathsAdd Digits

问题描述:

 

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

 

Example:

 

Input: 38
Output: 2 
Explanation: 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?

 

思路:

最暴力的思路是用循环,但是最后题目提示可以不用循环,以及运行时间O(1).

 

那么我们先来观察1到20的所有的结果:

 

1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8    
9    9    
10    1
11    2
12    3    
13    4
14    5
15    6
16    7
17    8
18    9
19    1
20    2

 

 

 

根据上面的列举,我们可以得出规律,每9个一循环,所有大于9的数的结果都是对9取余,其中9的倍数 对9取余就是0了,此时返回9;若非9的倍数,则返回余数。这里有个特殊情况,就是0, 0对9取余,得到的0,但是返回值却应该是0,所以这个需要特殊处理下。

 

代码:

 

1 class Solution:
2     def addDigits(self, num: int) -> int:
3         return 9 if num != 0 and num % 9 == 0 else num % 9

 

posted on 2019-07-16 15:06  狂奔的蜗牛163  阅读(194)  评论(0编辑  收藏  举报