Codewars JS习题:Sum of Digits / Digital Root

题目

In this kata, you must create a digital root function.

A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Here’s how it works (Ruby example given):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
digital_root(16)
=> 1 + 6
=> 7

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6

digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2

我的解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function digital_root(n) {
function sum(n) {
let arr = [];
let result = 0;
n = n + '';
for(let i of n) {
result += parseInt(i);
}
return result;
}
let res = sum(n);
if(res > 9) {
return sum(res);
} else {
return res;
}
}

思路:
因为结果需要一直重复轮加,直到最终结果小于10,所以会考虑到递归。在函数内部创建一个基础的函数,先算出n所有位数相加的结果,如果大于10,再对结果使用基础函数。
基础函数的思路是,先将参数数字n转换为字符串,使其具有可遍历性,然后轮加,求得最终结果,返回给digital_root函数。