Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sum of Digits / Digital Root #4

Open
hellocan opened this issue Apr 10, 2016 · 9 comments
Open

Sum of Digits / Digital Root #4

hellocan opened this issue Apr 10, 2016 · 9 comments

Comments

@hellocan
Copy link

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

@Go7hic
Copy link
Member

Go7hic commented Apr 10, 2016

function digital_root(n) {
   return String(n).split('').map(Number).reduce((i,j) => i+j)
}

@Go7hic
Copy link
Member

Go7hic commented Apr 10, 2016

不知道为啥这个答案过不了

@Go7hic
Copy link
Member

Go7hic commented Apr 10, 2016

哎呀,被你给的信息给误导了。看了原网站的题目才发现,是这个意思:

942
=> 9+4+2
=>15
=>1+5
=>6

是这个意思

@Go7hic
Copy link
Member

Go7hic commented Apr 10, 2016

来个递归就好了

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()
}

@Go7hic Go7hic closed this as completed Apr 10, 2016
@Go7hic Go7hic reopened this Apr 10, 2016
@hellocan
Copy link
Author

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())
}

@hellocan
Copy link
Author

哈哈,我粗心了。好像代码格式还是没有你的好看

@Go7hic
Copy link
Member

Go7hic commented Apr 11, 2016

这个题目排名最高的答案给我的感觉就是——程序的数学之美。

@Luffyying
Copy link

这个题目排名最高的答案给我的感觉就是——程序的数学之美。

能否解惑下这个答案呢,😂

@ool3
Copy link

ool3 commented Apr 12, 2020

хехе

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants