は、ウィキペディア
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
によると、私たちはそう
アカウントハッピーナンバー定義を考慮して、JavaScriptを捕捉されない例外RangeErrorをトロウになることを、私たちの数を渡しますしている再帰関数isHappy
を作成しました:最大呼び出しスタックサイズがを超えました。私たちは無限にループするときに、の中に関数を入れます... catchブロック、最終コード
//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
この1つをお待ちくださいhttps://gist.github.com/xk/8918502 –
ここ:http://www.w3resource.com/javascript-exercises/javascript-conditional-statements-and-loops-exercise-8.php –