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.
利用数字根的规律求解(Digital Root)
一个数的数字根是它除以9的余数(如果该数是9的倍数,那么该数的数字根就是9)
归纳为:dr(n)=1+(num-1)%9
public class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}