Project Euler #17: Number to Words

Question
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.

Answer : 21124

Hacker Rank Problem

Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();

        for (int a0 = 0; a0 < t; a0++) {
            int n = in.nextInt();
            System.out.println(toEnglish(n));
        }
    }

    public static String run(int number) {
        int sum = 0;
        for (int i = 1; i <= number; i++)
            sum += toEnglish(i).length();
        System.out.println(toEnglish(sum));
        return Integer.toString(sum);
    }


    private static String toEnglish(int n) {
        if (0 <= n && n < 20)
            return ONES[n];
        else if (20 <= n && n < 100)
            return TENS[n / 10] + (n % 10 != 0 ? ONES[n % 10] : "");
        else if (100 <= n && n < 1000)
            return ONES[n / 100] + "Hundred " + (n % 100 != 0 ? "" + toEnglish(n % 100) : "");
        else if (1000 <= n && n < 1000000)
            return toEnglish(n / 1000) + "Thousand " + (n % 1000 != 0 ? toEnglish(n % 1000) : "");
        else if (1000000 <= n && n < 1000000000)
            return toEnglish(n / 1000000) + "Million  " + (n % 1000000 != 0 ? toEnglish(n % 1000000) : "");
        else if (1000000000 <= n)
            return toEnglish(n / 1000000000) + "Billion  " + (n % 1000000000 != 0 ? toEnglish(n % 1000000000) : "");
        else
            throw new IllegalArgumentException();
    }


    private static String[] ONES = {
            "Zero ", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ",
            "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};

    private static String[] TENS = {
            "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
}

Comments

Popular Posts