问题
数字根是一个数字中所有数字的递归和。
给定n,取n的数字之和。如果该值有多个数字,则继续以这种方式减少,直到产生一个单位数字为止。这只适用于自然数。
我的代码
function digital_root(n) {
let a = n.toString();
let ai = a.split('');
let bi = ai.map((item)=>{
return parseInt(item);
})
let newArr = [];
for(let i = 0; i < bi.length; i++){
let c = bi[i];
newArr.push(c);
}
let d = newArr.reduce((total, item)=>{
return total + item;
}, 0);
function recursive(d){
if(d < 10){
return d
}
a = d.toString();
ai = a.split('');
bi = ai.map((item)=>{
return parseInt(item);
});
newArr = [];
for(let i = 0; i < bi.length; i++){
let c = bi[i];
newArr.push(c);
}
d = newArr.reduce((total, item)=>{
return total + item;
}, 0);
return recursive(d);
}
return d;
}
console.log(digital_root(123));
console.log(digital_root(111));
console.log(digital_root(51024));
我的问题
由于某些原因,代码似乎没有意识到,如果d >= 9,我需要再次运行该操作。
如何解决我已经完成的代码的问题?
同样出于兴趣,你会如何接近它,我的答案似乎相当复杂!
发布于 2020-06-11 12:55:17
您从未调用您创建的递归函数,请将return d替换为return recursive(d);
我是怎么做到的:
function digital_root(n){
return n < 10 ? n : digital_root(String(n).split('').reduce((acc,val) => acc+(val|0),0));
}发布于 2020-06-11 13:06:35
让我们发表一些评论,看看是怎么回事。
function digital_root(n) {
// convert multiple digit number to String
let a = n.toString();
// split the String into an array of single digit Strings
let ai = a.split('');
// convert String array into int array
let bi = ai.map((item)=>{
return parseInt(item);
})
// it looks like you are just copying the array here,
//I don't think there is a need for that
// let newArr = [];
// for(let i = 0; i < bi.length; i++){
// let c = bi[i];
// newArr.push(c);
// }
// reduce the int array to the sum of its digits
let d = bi.reduce((total, item)=>{
return total + item;
}, 0);
// That should be it, now just print it or recurse it
if (d < 10) {
return d;
}
// here is how you recurse, call the method from within the method
return digital_root(d);
// I'm not sure what you are doing here, you are repeating code
// this is not how recursion works
// function recursive(d){
// if(d < 10){
// return d
// }
// a = d.toString();
// ai = a.split('');
// bi = ai.map((item)=>{
// return parseInt(item);
// });
// newArr = [];
// for(let i = 0; i < bi.length; i++){
// let c = bi[i];
// newArr.push(c);
// }
// d = newArr.reduce((total, item)=>{
// return total + item;
// }, 0);
// return recursive(d);
// }
// return d;
}
console.log(digital_root(123));
console.log(digital_root(111));
console.log(digital_root(51024));
发布于 2020-06-11 12:57:06
除了光子所说的,这里还有一个更简单的解决方案
function sum(n) {
if (n <= 9) {
return n;
} else {
return sum((n % 10) + sum(n / 10));
}
}
>>> sum(156)
... 3
>>> sum(9999)
... 9
>>> sum(10)
... 1https://stackoverflow.com/questions/62324745
复制相似问题