###### tags: `Leetcode` `easy` `math` `python` `c++`
# 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.
**Follow up: Could you do it without any loop/recursion in O(1) runtime?**
**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
```
## 解題想法:
follow up:數學解 .......還未理解
可參考大神 [LeetCode 258 Add Digits (Python)]https://maxming0.github.io/2020/07/26/Add-Digits/
## Python: 一般loop解
``` python=
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while num>9:
cur=0
while num:
cur+=num%10
num//=10
num=cur
return num
if __name__ == '__main__':
result = Solution()
ans=result.addDigits(num = 38)
print(ans)
```
## C++: 一般loop解
``` cpp=
#include<iostream>
using namespace std;
class Solution {
public:
int addDigits(int num) {
while (num>9){
int cur=0;
while (num){
cur+=num%10;
num/=10;
}
num=cur;
}
return num;
}
};
int main(){
Solution res;
int nums=38;
int ans=res.addDigits(nums);
cout<<ans<<endl;
return 0;
}
```