计数 JavaScript 中的字母数
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数接受一个数字,例如 n。该函数应从 1 到 n 计数数字名称中的字母。
例如 − If n = 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));
输出
这将产生以下输出 −
51 19 1280