2013-08-04 56 views
0

這是項目歐拉問題#17,我試圖在JavaScript中。對我來說超級怪異的是,如果我在我的回答中調用typeof(),它會說這是一個「數字」。然後,如果我嘗試運行打印結果的函數,我會得到「NaN」Euler 17 Javascript

如果您知道1)解決我的代碼工作的方法和/或2)更好的方法來解決存在的問題(我不懷疑它的確如此),非常感謝建設性的批評!

var arrayOnes = [3,3,5,4,4,3,5,5,4]; 
var arrayTeens = [6,6,8,8,7,7,9,8,8]; 
var arrayTens = [3,6,6,5,5,5,7,6,6]; 
var arrayHundreds = [12,12,14,13,13,12,14,14,13]; 
var sum99 = 0; 
var sum999 = 0; 
var sum1000 = 11; 

function sumsOneToNineNine() { 
    for (i=1; i<=9; i++) { 
     sum99 += ((arrayOnes[i]*9) + arrayTeens[i] + arrayTens[i]); 
    } 
} 

function sumsOneToOneThousand() { 
    sumsOneToNineNine(); 
    for (i=1; i<9; i++) { 
    sum999 += arrayHundreds[i]; 
    } 
    sum999 += 9*sum99 + sum999; 
    sum1000 += sum999; 
    console.log(sum1000); 
} 

sumsOneToOneThousand(); 
+0

嘛,'NaN'是一個數值,根據規範,IEEE 754標準。 –

+0

'NaN'是*每種*語言的數字類型。爲什麼它在Javascript中「很奇怪」? – Esailija

+0

我剛剛意識到它應該是i-1而不是我的每一件事情,以解釋從0開始的索引,而不是1。現在我得到一個#答案,但它不是正確的答案。 –

回答

0

即使你說你覺得你能得到它,我想我會比發佈您呈現,這也可以很容易地擴展以及過去的千稍微清潔解決方案,即使問題並不需要它。

無論如何,青少年也有一個模式,其中5個長度與數字+ 10的名稱相同,因爲信件被丟棄,另外4個由於沒有被丟棄,所以是1個字母加長。一旦你超過100到9,999(是的,我知道這個問題並不需要它,但如果你想擴展到persay,10K),你可以重新使用這個地方數組,然後再使用這個數組,那麼當你進入10K-100K的範圍,重複使用十幾歲規則和十位陣列等

var lenHundred = 7; 
var lenThousand = 8; 
var lenPlaceOnes = [0,3,3,5,4,4,3,5,5,4]; 
var lenPlaceTens = [0,3,6,6,5,5,5,7,6,6]; 

function sumTo(num) { 
    var sum = 0; 

    for (var i = 1; i <= num; i++) { 
     var placeOnes = i % 10; 
     var placeTens = Math.floor(i/10) % 10; 
     var placeHundreds = Math.floor(i/100) % 10; 
     var placeThousands = Math.floor(i/1000) % 10; 

     // Add the ones place 
     sum += lenPlaceOnes[placeOnes]; 

     // Add the tens place 
     sum += lenPlaceTens[placeTens]; 

     // If the hundreds place is non-zero, add it and "hundred" 
     if (placeHundreds != 0) { 
      sum += lenHundred + lenPlaceOnes[placeHundreds]; 
     } 

     // If the thousands place is non-zero, add it and "thousand" 
     if (placeThousands != 0) { 
      sum += lenThousand + lenPlaceOnes[placeThousands]; 
     } 

     //////////////// 
     // TEENS RULE // 
     //////////////// 

     // If the number is in the teens, take care of special numbers 
     // Eleven is the same length as "oneten", Twelve the same as "twoten", and so on 
     // With the exception of those in the switch statement 
     if (placeTens == 1) { 
      // If the ones place is 4, 6, 7, or 9, add an extra 1 for the "e" 
      switch (placeOnes) { 
       case 4: 
       case 6: 
       case 7: 
       case 9: 
        sum += 1; 
        break; 
      } 
     } 

     ////////////// 
     // AND RULE // 
     ////////////// 

     // If the value is above one hundred, and the number is not an exact hundred, add 
     // 3 for the "and" 
     if (i > 100 && i % 100 != 0) { 
      sum += 3; 
     } 
    } 

    return sum; 
} 

console.log("Sum to Five Inclusive: " + sumTo(5)); 
console.log("Sum to 1K Inclusive: " + sumTo(1000));