Number to Words
Problem
Read an integer from 0 to 999999 and print it in English words. Use lower-case letters, a hyphen between tens and ones (twenty-one), and no word 'and'. Example: 123456 is one hundred twenty-three thousand four hundred fifty-six.
Constraints
- 0 <= n <= 999999
Examples
Input
123456
Output
one hundred twenty-three thousand four hundred fifty-six
Input
0
Output
zero
Solutions
Numbers are read in groups of three digits. One helper writes any number below 1000. The main code calls it for the thousands group and for the rest, and adds the word thousand between them.
/*
* Problem : Write a number in English words.
* Input : One integer from 0 to 999999.
* Output : The number in lower-case English words.
* Approach: Handle groups of three digits.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
static final String[] ONES = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
static final String[] TENS = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
// This method receives a number from 1 to 999 and returns it in words. Example: 345 -> "three hundred forty-five".
static String underThousand(int number) {
StringBuilder words = new StringBuilder();
// Step 1: Write the hundreds. Example: 345 / 100 = 3 -> "three hundred".
if (number >= 100) {
words.append(ONES[number / 100]).append(" hundred");
number = number % 100;
}
// Step 2: Write the rest (from 1 to 99). Add a space if something is written already.
if (number > 0) {
if (words.length() > 0) {
words.append(" ");
}
if (number < 20) {
// Step 2a: Numbers below 20 have their own words. Example: 14 -> "fourteen".
words.append(ONES[number]);
} else {
// Step 2b: Write the tens word. Example: 45 -> "forty". Add the ones with a hyphen. Example: "-five".
words.append(TENS[number / 10]);
if (number % 10 > 0) {
words.append("-").append(ONES[number % 10]);
}
}
}
return words.toString();
}
public static void main(String[] args) {
int number = new Scanner(System.in).nextInt();
// Step 3: Zero is a special case. The code below would write nothing.
if (number == 0) {
System.out.println("zero");
return;
}
// Step 4: Split the number into thousands and the rest. Example: 123456 -> 123 and 456.
int thousands = number / 1000;
int rest = number % 1000;
StringBuilder result = new StringBuilder();
// Step 5: Write the thousands part, then the word "thousand".
if (thousands > 0) {
result.append(underThousand(thousands)).append(" thousand");
}
// Step 6: Write the rest. Add a space if something is written already.
if (rest > 0) {
if (result.length() > 0) {
result.append(" ");
}
result.append(underThousand(rest));
}
System.out.println(result);
}
}
Hints (2)
- Write a helper for numbers below 1000 first.
- Numbers below 20 need their own words, tens need a different word list.