我正在使用Codewars问题'Happy Numbers'这是链接https://www.codewars.com/kata/happy-numbers-5/train/javascript这是问题,当我在n> 98时运行代码时已达到最大调用堆栈大小。如何对我的代码进行一些更改以解决此问题?
function happyNumbers(x){
var res = [];
for (let i = 1; i <= x; i++){
var str = [];
if (helper(str,i)){res.push(i)}
}
return res
}
function helper(str,n){
var num = 0;
if (n === 1){return true}
if (str.indexOf(n) > -1){return false}
str.push(n);
if (n.toString().length === 1){num = Math.pow(n,2).toString()}
if (n.toString().length >= 2){
num = n.toString().split('')
.reduce((a,b) => Math.pow(a,2)+ Math.pow(b,2)).toString();
}
return helper(str,Number(num))
}
一只斗牛犬
弑天下
随时随地看视频慕课网APP
相关分类