我正在尝试解决Persistent Bugger Kata。我已经编写了以下代码,但无法正确返回最终值。尽管它记录了正确的值。 我正在尝试使用递归。
const persistence = num => {
x = num.toString();
x = x.split('');
console.log(x);
if (x.length === 1) {
return parseInt(x.join());
// console.log(`num is ${x}`);
// return x;
}
if (x.length > 1) {
len = x.length;
arr = [];
for (i = 0; i < x.length; i++) {
if (i === 0) {
arr.push(x[i]);
} else {
arr.push(arr[0] * x[i]);
arr.shift();
}
num = parseInt(arr.join());
}
persistence(num);
}
};
我正在尝试返回最终值。
答案 0 :(得分:1)
您需要在return
之前添加persistence(num);
const persistence = num => {
x = num.toString();
x = x.split('');
console.log(x);
if (x.length === 1) {
return parseInt(x.join());
// console.log(`num is ${x}`);
// return x;
}
if (x.length > 1) {
len = x.length;
arr = [];
for (i = 0; i < x.length; i++) {
if (i === 0) {
arr.push(x[i]);
} else {
arr.push(arr[0] * x[i]);
arr.shift();
}
num = parseInt(arr.join());
}
return persistence(num);
}
};