# 第二次做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 {
return n-9*((n-1)/9);
}
}

• 本文已收录于以下专栏：

## LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]

LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]题目Given an array of integers where ...

## LeetCode [292. Nim Game] 难度[easy]

LeetCode [292. Nim Game] 难度[easy]题目You are playing the following Nim Game with your friend: There is...

## Leetcode - Math -258. Add Digits（数位求和，规律题）

1. Problem Description  Given a non-negative integer num, repeatedly add all its digits until the r...

## 刷leetcode过程中记录难度题，自己做法及最优做法

leetcode 41. First Missing Positive Given an unsorted integer array, find the first missing positiv...

## LeetCode的easy题集合(C++实现)二

1.Intersection of Two Linked Lists Write a program to find the node at which the inte...