将非负整数转换为其对应的英文表示,确保输入小于 2^31 - 1 。
示例 1:
输入: 123 输出: “One Hundred Twenty Three”
示例 2:输入: 12345 输出: “Twelve Thousand Three Hundred Forty Five”
示例 3:输入: 1234567 输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
这道题其实很简单,按照英文习惯将数字从低位到高位每三位划分,然后从高位到低位读数,单位分别为Billion Million Thousand;
另外注意一下10-19的读法即可
static String num1[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static String num2[] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
static String tens[] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
public String numberToWords(int num) {
if(num == 0){return "Zero";}
String result = "";
if(num > 999999999){
result += numberToWordsWithThreeDIgit(num/1000000000) + " Billion";
num %= 1000000000;
}
if(num > 999999){
result += numberToWordsWithThreeDIgit(num/1000000) + " Million";
num %= 1000000;
}
if(num > 999){
result += numberToWordsWithThreeDIgit(num/1000) + " Thousand";
num %= 1000;
}
if(num > 0){
result += numberToWordsWithThreeDIgit(num);
}
return result.trim();
}
public String numberToWordsWithThreeDIgit(int num) {
String result = "";
if(num > 99){
result += " " + num1[num / 100 - 1] + " Hundred";
}
num %= 100;
if(num>19){
result += " " + tens[num / 10 - 2];
num %= 10;
}else if(num>9){
result += " " + num2[num - 10];
num = 0;
}
if(num > 0){
result += " " + num1[num-1];
}
return result;
}