Euler 17 Javascript



这是针对项目Euler问题#17的,我正在javascript中尝试它。对我来说非常奇怪的是,如果我在答案上调用typeof(),它会说这是一个"数字"。然后,如果我试图运行打印结果的函数,我会得到"NaN"

如果你知道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();

尽管你说你认为你可以得到它,但我想我会发布一个比你提出的稍微干净的解决方案,它也可以很容易地扩展到一千以上,即使问题不需要它。

无论如何,这些青少年也有一种模式,其中5个与数字名称+10的长度相同,这是因为有一个字母掉了,而另外4个则是因为没有掉一个字母,所以长了1个字母

一旦你超过100到9999(是的,我知道这个问题不需要它,但如果你想把它扩展到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));

最新更新