0

这是针对项目 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();
4

1 回答 1

0

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

无论如何,青少年也有一个模式,其中 5 个与数字名称的长度相同 + 10,由于掉了一个字母,而另外 4 个,由于没有掉了一个字母,因此了 1 个字母。

一旦你超过 100 到 9,999(是的,我知道问题不需要它,但如果你想将它扩展到 persay,10K),你可以重新使用这些位置数组,然后当你得到进入10K-100K范围,重用teens规则和十位数组等。

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));
于 2013-08-04T21:35:03.117 回答