您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Add Digits

2015-08-17 00:11 609 查看

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?

Hint:

A naive implementation of the above process is trivial. Could you come up with other methods?

What are all the possible results?

How do they occur, periodically or randomly?

You may find this Wikipedia article useful.

数学题给跪了。

如果可以用循环,最好的情况是只读一遍。

贪心,每读一数都做Digit Root的操作,最后的结果是正确的。

/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
var str = num.toString(), res = 0, tmp1, tmp2;
for(var i = 0; i < str.length; i++){
res = parseInt(str[i]) + res;
if(res >= 10){
tmp1 = parseInt(res / 10);
tmp2 = res % 10;
res = tmp1 + tmp2;
}
}
return res;
};


最佳答案参照wiki : https://en.wikipedia.org/wiki/Digital_root

好几种写法都可以,这里列了2种。

/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
return num === 0 ? 0 : num - 9 * Math.floor((num - 1) / 9);
};


/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
return 1 + (num - 1) % 9;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: