# 273 Integer to English Words
把一個非負整數轉成英文。
Concept:
1234567
要從最小位數開始,每三位一個單位。
567 -> Five Hundred Sixty Seven
下一個三位
234 -> Two Hundred Thirty Four
後面要接 Thousand
-Main
20以下都是獨立的單字,從20以上開始需要組合,
所以用LESS_THAN_20來列舉20以下的數字,用TENS來列舉10,20,30...90。
用一個THOUSANDS陣列來列舉出Thousand, Million, Billion
THOUSANDS的index i每算完三位就++
並用一個helper function來計算千位以下的轉換
-helper(int num)
少於20的,從LESS_THAN_20取出來,
小於100的,取出TENS[num/10],再將num%10丟給helper
其他,取出LESS_THAN_20[num/100],接上Hundred,再將num%100丟給helper
private final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
public String numberToWords(int num) {
if (num == 0) return "Zero";
int i = 0;
String words = "";
while (num > 0) {
if (num % 1000 != 0)
words = helper(num % 1000) +THOUSANDS[i] + " " + words;
num /= 1000;
i++;
}
return words.trim();
}
private String helper(int num) {
if (num == 0)
return "";
else if (num < 20)
return LESS_THAN_20[num] + " ";
else if (num < 100)
return TENS[num / 10] + " " + helper(num % 10);
else
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
}