2017-07-25 56 views
1

这是我的代码来检查给定号码是Happy number。我想我正在尝试错误的逻辑。检查给定号码是否快乐

var num = 5239; 
 
var sum = 0; 
 
while (num > 0) { 
 
    sum += Math.pow(num % 10, 2); 
 
    num = Math.floor(num/10); 
 
    console.log(num) 
 
} 
 
console.log(sum); 
 
if (num == 0) { 
 
    alert("happy number") 
 
} else { 
 
    alert("Not happy number") 
 
}

请指正得到正确的结果。

+0

逻辑不正确。使用mod(%)函数计算num。 – Amit

+0

请将这一个https://gist.github.com/xk/8918502 –

+1

在这里:http://www.w3resource.com/javascript-exercises/javascript-conditional-statements-and-loops-exercise-8.php –

回答

1

https://jsfiddle.net/g18tsjjx/1/

如果我的理解是什么快乐数,这应该是正确的。

$(document).ready(function() { 
    var num = 1; 
    var i = 0; 
    for (i; i < 10000; i++) { 
    num = newNumber(num); 
    } 
    num == 1 ? alert("it's happy number") : alert("it's not happy number"); 
}); 

function newNumber(num) { 
    var sum = 0; 
    var temp = 0; 
    while (num != 0) { 
    temp = num % 10; 
    num = (num - temp)/10; 
    sum += temp * temp; 
    } 
    return sum; 
} 
+0

在你的代码中的小修正:将'if-else'条件放在'for()循环外部。 – krish

+0

@krish谢谢我整理了代码。 –

0

我怕你被误读的条件:它应该首先检查的最终数目为=== 1的。

而且你不应该只进行一次迭代,而是继续下去,直到你达到1或遇到已经解析的数字。我会建议使用散列来跟踪已有的seen数字。

只是不做免费的一些作业,递归here一个很好的例子。

1

根据维基百科

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). wikipedia Happy number

我创建递归函数isHappy对此,我们将通过我们的,所以
考虑到帐户快乐数定义和JavaScript就特罗未捕获的RangeError:最大调用堆栈大小超过的时候我们会无休止地循环,我们会把函数放在里面试试... catch block,所以这里是最后的代码

//Our Recursive Function 
function isHappy(number){ 

    var output = [], 
    sNumber = number.toString(); 

for (var i = 0, len = sNumber.length; i < len; i += 1) { 

    output.push(+sNumber.charAt(i));//converting into number 

    } 
    var sum=0; 

for(var i=0;i<output.length;i++){ 
    sum+=Math.pow(output[i],2); 
    } 

if(sum!==1){ 
    isHappy(sum); 

    } 

} 



try{ 
     isHappy(number);//call the function with given number 
     alert('happy') 

    }catch(err){ 
    alert('unhappy') 
    }