题目:
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?
思路:
- 用循环来想是比较简单的,但是对于复杂度有要求,那就一定有规律。
- 第一个开始计算的两位数就是10,从10开始逐次加一,9个一循环,就可以想出 num_return = (num-10)%9+1=(num-1)%9+1。
- return 1+(num)%9