LeetCode 258. Add Digits
題目
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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
翻譯
將一個數字每個位數相加,直到剩個位數為止。
範例:
num = 38,則 3+8 = 11,1+1 = 2, 2是個為數,回傳2。
進階:
不用迴圈,遞迴解這個問題
想法
轉陣列跑迴圈或是遞回加起來當小於10就可以return, 進階的有參考公式, 除9的餘數
詳細參閱
https://en.wikipedia.org/wiki/Digital_root
https://discuss.leetcode.com/topic/26300/elegant-3-line-recursion-c
Code
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
//代表只有個位數, 可直接跳出
if (num < 10) {
return num;
}
let str = String(num).split('');
let len = str.length - 1;
let i = 0 ;
//ex : [1, 2, 3] => [1, 3, 6]
var array_sum = str.map(function(val){
i += parseInt(val);
return i;
});
//取陣列最後一位
return addDigits(array_sum[len]);
};
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
if (num > 9) {
num = addDigits(parseInt(num / 10) + num % 10);
}
return num;
};
Run
Your input
0
234
152
1
99
9
Your answer
0
9
8
1
9
9
Expected answer
0
9
8
1
9
9
Runtime: 112 ms
留言
張貼留言