I need a Recursive algorithm to spell out any number from 1 to 2.1 billion. I already have the main part of the program sorted out but I am having trouble working Strings into the spelled out number.
For example 1,234,567 prints: "one thousand two hundred thirty four million five hundred sixty seven"
I understand why it is printing "thousand" before "million", I'm just having trouble finding the correct way to work in "hundred", "thousand", "million", and "billion" so that they are in the correct order. Thanks in advance.
static String[] numbers = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "ninteen", "twenty"};
static String[] tens = {"twenty-", "thirty-", "fourty-", "fifty-",
"sixty-", "seventy-", "eighty-", "ninety-"};
//static String[] hundreds = {"hundred", "thousand", "million", "billion"};
private static String say(int n) {
if (n <= 20) {
return numbers[n];
}
else if (n < 100) { // 99
return tens[(n / 10) - 2] + say(n % 10); // TODO: fix seventy-zero
}
else if (n < 1000) { // 999 max
return say(n / 100) + " hundred " + say(n % 100);
}
else if (n < 1000000) { // 999,999 max
return say(n / 1000) + " thousand " + say(n % 1000);
}
else if (n < 1000000000) { // 999,999,999 max
return say(n / 1000) + " million " + say(n % 1000);
}
else if (n <= 2147483647) { // 2,147,483,647 max integer value
return say(n / 1000) + " billion " + say(n % 1000);
}
else
return "error";
}