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.
Follow up: Could you do it without any loop/recursion in O(1) runtime?
Solution
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
var res = 0;
while (num) {
res += num % 10;
num = Math.floor(num / 10);
}
return res < 10 ? res : addDigits(res);
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).
Solution
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
return 1 + (num - 1) % 9;
};
Explain:
结果只有一个数字,就是 1~9
,不断循环,找规律即可。
Complexity:
- Time complexity : O(1).
- Space complexity : O(1).