CNode

关于codewars上的一道js题?

问答
QQuoniamYIF发布于11 年前最后回复11 年前2 回复5216 浏览0 收藏

题目:

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

我的解法很普通:

function digital_root(n) {
	  while(n > 10 ) {
	    var n = n.toString().split('').reduce(function (s, v) {return Number(s)+ Number(v)});
	  }
	  return n;
}

很酷的解法:

function digital_root(n) {
  return (n - 1) % 9 + 1;
}

但是并没有看懂,谁能帮我解答一下原理,谢谢了?

原题链接

查看回复

回复 (2)

S
struCoder#1·11 年前

很简单啊 任何一个多位数数的各个位数相加,再将结果的各个位数相加...,直到得到一位数,那么这个一位数一定是原本的那个数除以9的余数. 而本身就是个位数的数字只要不是9都不能整除9只能余 以此类推,你把多位数的数字用加法拆开然后分别除以9,得到的余数相加再除以9 以此类推就是最后的结果了 这里之所以要先(n - 1) 得到余数后再加 1是应为处理这个数是9的特殊情况。

Q
QuoniamYIF#2·11 年前

懂了,十分感谢

参与回复
登录后即可参与回复。登录