此算法的目标是取一个数字的每个数字的平方,将它们加在一起,然后继续重复直到返回数字1
。我确定算法可以工作,但是我无法完全了解return
。为什么这行不通?
const n = 19;
const sumSquare = (n) => {
const N = n.toString();
let sum = 0;
for (let digit of N) {
const product = +digit * +digit;
sum += product;
}
console.log(sum);
if (sum === 1) {
return true;
} else {
sumSquare(sum);
}
};
console.log(sumSquare(n));
答案 0 :(得分:7)
您需要return sumSquare(sum);
,然后将以返回值true
结束,如下所示:
const n = 19;
const sumSquare = (n) => {
const N = n.toString();
let sum = 0;
for (let digit of N) {
const product = +digit * +digit;
sum += product;
}
console.log(sum);
if (sum === 1) {
return true;
} else {
return sumSquare(sum);
}
};
console.log('result:', sumSquare(n));
我们还可以简化整个if语句,使其看起来像这样:
return sum === 1 || sumSquare(sum);
const n = 19;
const sumSquare = (n) => {
const N = n.toString();
let sum = 0;
for (let digit of N) {
const product = +digit * +digit;
sum += product;
}
console.log(sum);
return sum === 1 || sumSquare(sum);
};
console.log('result:', sumSquare(n));