Euler Project – Problem 17 solution

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.

public class Main {

    static String[] numbers_under_twenty = new String[]{"", "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine",
            "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
            "sixteen", "seventeen", "eighteen", "nineteen"};
    static String[] tens = new String[]{"", "ten", "twenty", "thirty","forty","fifty",
            "sixty","seventy","eighty","ninety"};
    static String hundred = "hundred";
    static String thousand = "thousand";
    static String and = "and";
   
    public static void main(String[] args) {
       
        int sum = 0;
        for (int i = 1; i <= 1000; i++) {
            sum+=getLettersCount(i);
        }
        System.out.println(sum);
       
    }

    private static int getLettersCount(int num) {

        int letters_count = 0;
       
        if(num%100<20){
            letters_count += numbers_under_twenty[num%100].length();
        }
        else
        {
            letters_count += numbers_under_twenty[num%10].length();
            letters_count += tens[(num%100-num%10)/10].length();
        }
       
        if(num>=100 && num<1000){
            letters_count += numbers_under_twenty[(num%1000-num%100)/100].length();
            letters_count += hundred.length();
            if(num%100!=0){
                letters_count+=and.length();
            }
        }
       
        if(num==1000){
            letters_count += numbers_under_twenty[1].length();
            letters_count += thousand.length();
        }

        return letters_count;
    }
   
}