计数JavaScript中的字母数
我们需要编写一个带数字(例如n)的JavaScript函数。该函数应计算数字名称中从1到n的字母。
例如-如果n = 5;
那么数字是1、2、3、4、5,字母总数是19,所以输出应该是19。
示例
const sumUpto = (num = 1) => {let sum = 0;
const lenHundred = 7;
const lenThousand = 8;
const lenPlaceOnes = [0,3,3,5,4,4,3,5,5,4];
const lenPlaceTens = [0,3,6,6,5,5,5,7,6,6];
for (let i = 1; i <= num; i++) {
let placeOnes = i % 10;
let placeTens = Math.floor(i / 10) % 10;
let placeHundreds = Math.floor(i / 100) % 10;
let placeThousands = Math.floor(i / 1000) % 10;
sum += lenPlaceOnes[placeOnes];
sum += lenPlaceTens[placeTens];
if (placeHundreds != 0) {
sum += lenHundred + lenPlaceOnes[placeHundreds];
}
if (placeThousands != 0) {
sum += lenThousand + lenPlaceOnes[placeThousands];
}
if (placeTens === 1) {
switch (placeOnes) {
case 4:
case 6:
case 7:
case 9:
sum += 1;
break;
}
}
if (i > 100 && i % 100 != 0) {
sum += 3;
}
}
return sum;
}
console.log(sumUpto(12));
console.log(sumUpto(5));
console.log(sumUpto(122));
输出结果
这将产生以下输出-
5119
1280
以上是 计数JavaScript中的字母数 的全部内容, 来源链接: utcz.com/z/338040.html