即使你说你认为你可以得到它,我想我会发布一个比你提出的稍微干净的解决方案,即使问题不需要它,它也可以很容易地扩展到超过一千。
无论如何,青少年也有一个模式,其中 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));