Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.这个题目就是说不断的把整数拆分成个位数再相加,直到不能相加为止,要求复杂度是
O(1)
。 那么可以采用递归算法再来做。
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
if(num<10)return num;
else return addDigits(addDigits(Math.floor(num/10))+num%10);
};