Add Digits Problem
Description
LeetCode Problem 258.
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
1
2
3
4
5
6
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:
1
2
Input: num = 0
Output: 0
Constraints:
- 0 <= num <= 2^31 - 1
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int addDigits(int num) {
int sum = 0;
while (num > 9) {
while(num) {
sum += (num % 10);
num /= 10;
}
num = sum;
sum = 0;
}
return num;
}
};