根据维基百科
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')
}
逻辑不正确。使用mod(%)函数计算num。 – Amit
请将这一个https://gist.github.com/xk/8918502 –
在这里:http://www.w3resource.com/javascript-exercises/javascript-conditional-statements-and-loops-exercise-8.php –