258.Add Digits
===
###### tags: `Easy`,`Math`
[258. Add Digits](https://leetcode.com/problems/add-digits/)
### 題目描述
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
### 範例
**Example 1:**
```
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
```
**Example 2:**
```
Input: num = 0
Output: 0
```
**Constraints**:
* 0 <= `num` <= 2^31^ - 1
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
### 解答
#### Javascript
```javascript=
function addDigits(num) {
if (num < 10) return num;
return addDigits((num % 10) + addDigits(Math.floor(num / 10)));
}
```
> [name=Marsgoat][time=Apr 26, 2023]
```javascript=
function addDigits(num) {
return ((num - 1) % 9) + 1;
}
```
> 吉神:這題O(1)不是基本嗎?9的倍數檢查方式不是國小教的嗎??
> 我道歉嗚嗚嗚,我就爛。
> [name=Marsgoat][time=Apr 26, 2023]
#### C++
```cpp=
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
```
> [name=Yen-Chi Chen][time=Wed, Apr 26, 2023]
#### Python
```python=
class Solution:
def addDigits(self, num: int) -> int:
return (num - 1) % 9 + 1 if num else 0
```
> [name=Yen-Chi Chen][time=Wed, Apr 26, 2023]
#### C#
```csharp=
public int AddDigits(int num) {
if (num == 0) return 0;
int r = num % 9;
return r == 0 ? 9 : r;
}
```
> [name=Jim][time=Wed, Apr 26, 2023]
\begin{split}
&x_n10^n+x_{n-1}10^{n-1} +...+x_110+x_0\\&=x_n(9+1)^n+x_{n-1}(9+1)^{n-1} +...+x_1(9+1)+x_0\\&=9(...) +(x_n+x_{n-1}+...+x_1 +x_0)
\end{split}
忘了怎麼排版...
#### Java
```java=
class Solution {
public int addDigits(int num) {
return num != 0 ? (num - 1) % 9 + 1 : 0;
}
}
```
> [name=Ron Chen][time=Mon, Jun 12, 2023]
### Reference
[排版教學](https://hackmd.io/@sysprog/B1RwlM85Z?type=eidt#LaTeX-%E6%8E%92%E7%89%88)
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)