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 more than one digit, 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:
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 …
=> 2 + 9
=> 11 …
=> 1 + 1
=> 2
翻译(来自有道翻译):
在这个kata中,您必须创建一个数字根函数。
数字根是数字中所有数字的递归和。给定n,取n个数字的和。如果该值有多个数字,则继续以这种方式递减,直到产生一个个位数为止。这只适用于自然数。
它是这样工作的:
digital_root (493193)
=> 4 + 9 + 3 + 1 + 9 + 3
= > 29…
=> 2 + 9
= > 11……
=> 1 + 1
= > 2
个人解题代码:
//思路:通过累加循环进行计算,最后返回值
function digital_root(n) {
function allSum(n){
var str = n.toString();
var sum = 0;
for(let i of str){
sum += parseInt(i);
}
return sum;
}
var res = allSum(n)
if(res>9){
return allSum(res)
}else{
return res
}
}
高亮答案:
function digital_root(n) {
return (n - 1) % 9 + 1;
}