Problem
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
Code
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int addDigits(int num) {
if(num/10 == 0)
return num;
int temp = 0;
while(num!=0){
temp += num % 10;
num = num / 10;
}
return addDigits(temp);
}
};
Result
image.png