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
. Since2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Related Topics:
Math
Similar Questions:
See explanation in https://leetcode.com/problems/add-digits/solution/.
// OJ: https://leetcode.com/problems/add-digits/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int addDigits(int num) {
return num ? (num % 9 ? num % 9 : 9) : 0;
}
};
Or
// OJ: https://leetcode.com/problems/add-digits/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int addDigits(int num) {
return num ? 1 + (num - 1) % 9 : 0;
}
};