(See also the next iteration.)
I have rolled this short program that converts int
values to the human readable strings:
package com.github.coderodde.fun;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class IntToHumanReadableStringConverter {
private static final Map<Integer, String> TENS_MAP = new HashMap<>();
static {
TENS_MAP.put(1, "one");
TENS_MAP.put(2, "two");
TENS_MAP.put(3, "three");
TENS_MAP.put(4, "four");
TENS_MAP.put(5, "five");
TENS_MAP.put(6, "six");
TENS_MAP.put(7, "seven");
TENS_MAP.put(8, "eight");
TENS_MAP.put(9, "nine");
TENS_MAP.put(10, "ten");
TENS_MAP.put(11, "eleven");
TENS_MAP.put(12, "twelve");
TENS_MAP.put(13, "thirteen");
TENS_MAP.put(14, "fourteen");
TENS_MAP.put(15, "fifteen");
TENS_MAP.put(16, "sixteen");
TENS_MAP.put(17, "seventeen");
TENS_MAP.put(18, "eighteen");
TENS_MAP.put(19, "nineteen");
TENS_MAP.put(20, "twenty");
TENS_MAP.put(30, "thirty");
TENS_MAP.put(40, "fourty");
TENS_MAP.put(50, "fifty");
TENS_MAP.put(60, "sixty");
TENS_MAP.put(70, "seventy");
TENS_MAP.put(80, "eighty");
TENS_MAP.put(90, "ninety");
}
public static String convert(int num) {
StringBuilder sb = new StringBuilder();
if (num < 0) {
sb.append("minus ");
num = -num;
}
int billions = num / 1_000_000_000;
num -= billions * 1_000_000_000;
int millions = num / 1_000_000;
num -= millions * 1_000_000;
int thousands = num / 1_000;
num -= thousands * 1_000;
int units = num;
if (billions > 0) {
sb.append(convertUnitsImpl(billions));
sb.append(" billion ");
}
if (millions > 0) {
sb.append(convertHundredsImpl(millions));
sb.append(" million ");
}
if (thousands > 0) {
sb.append(convertHundredsImpl(thousands));
sb.append(" thousand ");
}
if (units > 0) {
sb.append(convertHundredsImpl(units));
}
return sb.toString();
}
private static String convertUnitsImpl(int unit) {
return TENS_MAP.get(unit);
}
// Converts a num in range [0, 999] to the human readable string:
private static String convertHundredsImpl(int num) {
StringBuilder sb = new StringBuilder();
int hundreds = num / 100;
num -= 100 * hundreds;
if (hundreds > 0) {
sb.append(convertUnitsImpl(hundreds));
sb.append(" hundred ");
}
if (num > 0) {
String tensString = TENS_MAP.get(num);
if (tensString == null) {
int units = num % 10;
num -= units;
sb.append(TENS_MAP.get(num));
sb.append("-");
sb.append(convertUnitsImpl(units));
} else {
sb.append(tensString);
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int num = scanner.nextInt();
String s = convert(num);
System.out.println(s);
}
}
}
For example, when I input -123456
, I get minus one hundred twenty-three thousand four hundred fifty-six
.
Critique request
As always, I would like to hear whatever comes to mind.