题目链接:https://leetcode.com/problems/integer-to-english-words/
题目
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 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”
解题思路
注:翻译规律与正常英文格式不同,没有and,0不表示出来。
PS:看到题第一反应是罗马数字和int互相转换的题。
翻译规律有自己的名词表,自然会考虑表驱动;英文中三位一个间隔,分thousand、million、billion、trillion,所以处理的时候也是三位为一个处理单元;题目规定最大为2^31-1,billion就够了。
代码
private String[] numberName = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" ,"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
private String[] tensName = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"};
private String[] thousandsName = {"","Thousand","Million","Billion","Trillion"};
public String numberToWords(int num) {
if(num == 0){
return "Zero";
}
String tmp = num + "";
String res = "";
for(int i = 0; i <= (tmp.length() - 1) / 3; i++){
int startIndex = tmp.length() < (i + 1) * 3 ? 0 : tmp.length() - (i + 1) * 3;
String toWord = threeToWords(Integer.parseInt(tmp.substring(startIndex, tmp.length() - i * 3)));
if(toWord.length() != 0){
res = toWord + " " + thousandsName[i] + " " + res;
}
}
return res.trim();
}
private String threeToWords(int num){
if(num == 0){
return "";
}
String res = "";
if(num / 100 != 0){
res = numberName[num / 100] + " Hundred";
}
int tmp = num % 100;
if(tmp < 20){
res = res + " " + numberName[tmp];
}else{
res = res + " " + tensName[tmp / 10] + " " + numberName[tmp % 10];
}
return res.trim();
}
写的时候思路不清,导致代码很乱,调好以后又懒得改,凑合着看吧= =