# Hard-题目49：273. Integer to English Words

142人阅读 评论(0)

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,
123 -> “One Hundred Twenty Three”
12345 -> “Twelve Thousand Three Hundred Forty Five”
1234567 -> “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

public class Solution {
public String[][] words = {
{"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}, // 0 stand for 0-9
{"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}, //1 stands for 11-19
{"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"} //2 stands for 10-90,please remember 'ninty' is WRONG.
};
public String numberToWords(int num) {
if(num == 0)
return "Zero";
String result = "";
if(num > 0 && num < 1000) {
result=numberToWords_1_1000(num);
}
else if(num >= 1000 && num < 1000000) {
result = numberToWords_1_1000(num/1000)+" Thousand";
if(num%1000!=0)
result = result + " "+numberToWords_1_1000(num%1000);
}
else if(num >= 1000000 && num < 1000000000) {
result = numberToWords_1_1000(num/1000000)+" Million";
if((num%1000000)/1000!=0)
result=result+" "+numberToWords_1_1000((num%1000000)/1000)+" Thousand";
if(num%1000!=0)
result=result+" "+numberToWords_1_1000(num%1000);

}
else {
result = numberToWords_1_1000(num/1000000000)+" Billion";
if((num%1000000000)/1000000!=0)
result=result+" "+numberToWords_1_1000((num%1000000000)/1000000) + " Million";
if((num%1000000)/1000!=0)
result=result+" "+ numberToWords_1_1000((num%1000000)/1000)+" Thousand";
if(num%1000!=0)
result=result+" "+numberToWords(num%1000);
}
return result;
}
private String numberToWords_1_100(int num) {
if(num<10) // num=0 is a special case,return "" in order to recrusively call it.
return words[0][num];
else if(num == 10)
return words[2][0]; //return "Ten"
else if(num < 20) // 11~19
return words[1][num-11];
else if(num % 10 == 0) // 20,30,...90
return words[2][num/10-1];
else
return words[2][num/10-1]+" "+words[0][num%10];
}
private String numberToWords_1_1000(int num) {
if(num<100)
return numberToWords_1_100(num);
else if(num==100)
return "One Hundred";
else if(num%100==0)
return words[0][num/100]+" Hundred";
else if(num>100 && num<200)
return "One Hundred "+numberToWords_1_100(num%100);
else
return words[0][num/100]+" Hundred "+numberToWords_1_100(num%100);
}
}

6ms,12.89%,5ms,44.43%
cmershen的碎碎念：

ninteen和ninty根本不存在！也不知道谁教出来的这两个词，尤其是ninty。

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：57027次
• 积分：3213
• 等级：
• 排名：第10664名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论