Open hellocan opened 8 years ago
function digital_root(n) {
return String(n).split('').map(Number).reduce((i,j) => i+j)
}
不知道为啥这个答案过不了
哎呀,被你给的信息给误导了。看了原网站的题目才发现,是这个意思:
942 => 9+4+2 =>15 =>1+5 =>6
是这个意思
来个递归就好了
function digital_root(n) {
var fn = function() {
return String(n).split('').map(Number).reduce((i,j) => i+j)
}
return fn() > 9 ? digital_root(fn()) : fn()
}
function digital_root(n) {
var root = function(){
return String(n).split('').map(Number).reduce((x,y) => x+y)
}
return n <= 9 ? root(n) : digital_root(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): 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
Your Test Cases: Test.assertEquals( digital_root(16), 7 )
where By http://www.codewars.com/kata/541c8630095125aba6000c00/train/javascript