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 <= 231 - 1
My Solution
We can solve this with two loops. We have one loop check that num >= 10 before proceeding to determine if it has more than 1 digit. In the inner loop we just add all the digits and update n.
Time complexity would be O(1) because there are more or less a constant number of digits in a 32 bit integer and we will converge in very few iterations no matter what initial number we choose. Space complexity is O(1) since we only require constant extra space.
class Solution {
public int addDigits(int num) {
while (num >= 10) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
return num;
}
}