2017-07-25 60 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') 
    }