273. Integer to English Words
T: O(n), the total only loop entire number length n
S: O(1), only ouput String and static array
class Solution {
private static String[] belowTen = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private static String[] belowTwenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private static String[] belowHundred = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
return helper(num);
}
private String helper(int num) {
StringBuilder result = new StringBuilder();
if (num < 10) {
result.append(belowTen[num]);
} else if (num < 20) {
result.append(belowTwenty[num - 10]);
} else if (num < 100) {
result.append(belowHundred[num/10]).append(" ").append(helper(num%10));
} else if (num < 1000) {
result.append(helper(num/100)).append(" Hundred ").append(helper(num%100));
} else if (num < 1000000) {
result.append(helper(num/1000)).append(" Thousand ").append(helper(num%1000));
} else if (num < 1000000000) {
result.append(helper(num/1000000)).append(" Million ").append(helper(num%1000000));
} else {
result.append(helper(num/1000000000)).append(" Billion ").append(helper(num%1000000000));
}
return result.toString().trim();
}
}
/*
Input: num = 1,234,567
Output: "One [Million] Two Hundred Thirty Four [Thousand] Five Hundred Sixty Seven"
1,234,567
1,000,010
1,234,234,234
One [Billion] Two Hundred Thirty Four [Million] Two Hundred Thirty Four [Thousand] Two Hundred Thirty Four
1,099,099,099
One [Billion] "" Ninety nine [Million] Ninety nine [Thousand] Ninety nine
1,000,000,000
One [Billion] => zero is ""
*/
Last updated