第二次做leetcode中的难度为easy的题-258

Total Accepted: 45239 Total Submissions: 95297 Difficulty: Easy
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.
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.https://en.wikipedia.org/wiki/Digital_root

public static int DigitalRoot(int n){
int m=0;
while(n!=0){
m=m+n%10;
n=n/10;
}
if (m<10){
return m;
}else{
return DigitalRoot(m);//递归
}

}

1.一个数的数根加9等于这个数的数根；

2.一个数乘以9之后的数根为9；（说明如果一个数是9的倍数，那么它的根为9）

3.$\mathit{dr}(a+b) \equiv \mathit{dr}(\mathit{dr}(a)+\mathit{dr}(b) ).$

4.$\mathit{dr}(a \times b) \equiv \mathit{dr}(\mathit{dr}(a)\times\mathit{dr}(b) ).$

public class Solution {
if(n%9>0||n==0){ //注意边界
return n%9;
}else{
return 9;
}
}
}

public class Solution {