Number of letters in the counting JavaScript

We are required to write a JavaScript function that takes in a number, say n. The function should count the letters in the number names from 1 to n.

For example ? If n = 5;

Then the numbers are one, two, three, four, five. And the total number of letters are 19, so the output should be 19.

How It Works

The algorithm uses arrays to store the letter count for each digit position and handles special cases like teens (11-19) and compound numbers (hundred, thousand).

Example

const sumUpto = (num = 1) => {
    let sum = 0;
    const lenHundred = 7; // "hundred" = 7 letters
    const lenThousand = 8; // "thousand" = 8 letters
    
    // Letter counts for ones place: 0, one, two, three, four, five, six, seven, eight, nine
    const lenPlaceOnes = [0,3,3,5,4,4,3,5,5,4];
    
    // Letter counts for tens place: 0, ten, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
    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;
        
        // Add letters for ones and tens
        sum += lenPlaceOnes[placeOnes];
        sum += lenPlaceTens[placeTens];
        
        // Add "hundred" + digit if hundreds place exists
        if (placeHundreds != 0) {
            sum += lenHundred + lenPlaceOnes[placeHundreds];
        }
        
        // Add "thousand" + digit if thousands place exists
        if (placeThousands != 0) {
            sum += lenThousand + lenPlaceOnes[placeThousands];
        }
        
        // Handle special cases for teens (11-19)
        if (placeTens === 1) {
            switch (placeOnes) {
                case 4: // fourteen
                case 6: // sixteen
                case 7: // seventeen
                case 9: // nineteen
                    sum += 1; // Extra letter for these cases
                    break;
            }
        }
        
        // Add "and" (3 letters) for numbers > 100 that aren't multiples of 100
        if (i > 100 && i % 100 != 0) {
            sum += 3;
        }
    }
    return sum;
}

console.log(sumUpto(12));
console.log(sumUpto(5));
console.log(sumUpto(122));

Output

51
19
1280

Key Points

The function handles:

  • Basic digit counting using lookup arrays
  • Special teen numbers (11-19) which have irregular spelling
  • Compound words like "one hundred and twenty-three"
  • The word "and" for numbers above 100

Conclusion

This algorithm efficiently counts letters in English number names by breaking numbers into digit positions and using lookup tables for letter counts. It handles special cases and compound number formats correctly.

Updated on: 2026-03-15T23:19:00+05:30

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements