我的代码有效,但计数不正确。例如,它正在考虑 22 和 208 作为happy numbers,但它们不是。{{3}}。乘法结果也是错误的:在 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;
}
答案 0 :(得分:1)
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')
}
}
}
答案 1 :(得分:1)
您可以使用较少的变量稍微更改代码,并使用break
退出。
基本上你不需要迭代获得正方形,然后另一个循环来获得正方形的总和。使用数组a
及其以前的值是错误结果的原因。
function isHappy(x) {
var b = x,
str,
dejavue = [],
sum,
result;
while (true) {
str = b.toString();
sum = 0;
for (var i = 0; i < str.length; i++) {
sum += str[i] * str[i];
}
if (dejavue.indexOf(sum) !== -1) {
result = " is not happy";
break;
}
dejavue.push(sum);
if (sum === 1) {
result = " is happy";
break;
}
b = sum;
}
return dejavue.join('>') + ": " + x + result;
}
console.log(isHappy(22));
console.log(isHappy(7));
&#13;