根據維基百科
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 –