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?
-----------------------------------------------------------------------------------------------------------------------
这道题最简单的思路是用循环,但是题目要求不能用,所以需要另寻它法。
对num展开 38=3*10+8 ,那么它的数字根就是 3+8。 对num变形 38=3*10+8 ==> 38=(3+8)+3*9。
那么为了求数字根,可以对num进行模9 : 38%9 = (3+8)%9+0。
考虑到如果数字根为9时求模后会等于0,则首先对num减1再求模,然后在加1。
则38的数字根 (38-1)%9+1 = 2.
代码如下:
public class Solution {
public int addDigits(int num) {
return 1 + (num-1)%9;
}
}