gpt4 book ai didi

Javascript Happy Number 检测错误

转载 作者:行者123 更新时间:2023-12-01 02:12:47 24 4
gpt4 key购买 nike

我的代码可以工作,但计数不正确。例如,它将 22208 视为 happy numbers ,但他们不是。乘法结果也是错误的:42之后不是20,而是45

    function isHappy(x){
var b = x,
str = b.toString(),
strlen = str.length,
a = [],
dejavue = [],
sum = 0,
isOne = false,
result,
whilenumber = -1;

while (isOne == false){
whilenumber++;
for (var i=0;i<strlen;i++){
var ms = parseInt(str[i]);
a[i] = ms*ms;
//a[i] = Math.pow(ms, 2);
}
if (a.length>1){
for (var i=0;i<a.length;i++){
sum = sum + a[i];
}
} else { sum = a[0];}
var h = dejavue.indexOf(sum);
if (h==-1) {dejavue[whilenumber] = sum;} else {
result = " is not happy";
break;
}
if (sum!=1){
b = sum;
sum = 0;
str = b.toString();
strlen = str.length;
}else{
result = " is happy";
isOne = true;
}
}
return dejavue+"_"+x+result;
}

最佳答案

var l = 50;
a=n=>{if((r=[...(n+'')].map(t=>t*t).reduce((a,b)=>a+b))==1){alert('happy')}else{if(l){l--;a(r)}else{alert('unhappy')}}
}

a(22)

/* explanation */

// how many times we want our function to run ultil decide is a unhappy number. This is to avoid infinite loop
var l = 50;

// parameter n = positive integer
n=>{
if(
//convert integer to string and split each char into an array
(r=[...(n+'')]
// get each separated number its square
.map(t=>t*t)
// sum squares
.reduce((a,b)=>a+b))
//if result is equal to one
== 1
){
// we alert happy
alert('happy')
}else{
//otherwise we check if our loop counter (l) aint done looping
if(l){
// if it does, then we substract 1 from the counter and call this same function with the result of the above operation
l--;a(r)
}else{
// otherwise is a unhappy number
alert('unhappy')
}
}
}

关于Javascript Happy Number 检测错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49651305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com