leetcode| Integer to English Words
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"
题目:意思很明确,就是将int整数转换成英文数字,difficulty为Hard,我居然解出来了~
思路:说到英文数字表示方法,最大的特点莫过于,每一千是一个节点,三个0为一个读取单词,1000以下则是另一套构词规则,所以首先我想
的是,1000以下搞一套方法,1000以上以这套方法为基础再搞一套,加上各种特出情况的判断,以下:
public String numberToWords(int num) {
if(num==0) return "Zero";
String letters [][] = {{""},{"Thousand"},{"Million"},{"Billion"}};
String res = "";
String numStr = num +"";
int len = numStr.length();
int count = len /3 ;
if(len <= 3){//三位数的时候用这个方法
return nTw3(num);
}else{//超过三位数,另作处理,每三位截一次,也就是每一个计数单位处理一次
String temp = "";int begin = len-3,end = len;
for(int i = 0;i < count+1;i++){
temp = numStr.substring(begin, end);
int t = 0;
if(temp.length()!=0){
t = Integer.parseInt(temp);
}
String ntw3 =nTw3(t);//还是要调用一下这个方法
if(ntw3.trim().length()!=0){
res = ntw3 +" "+letters[i][0]+" "+res;
}
end = begin;begin = begin-3 < 0?0:begin-3;
}
}
return res.replaceAll(" +"," ").trim();//出来的结果把多余的空格替换一下
}
private String nTw3(int num){
String letters [][] = {
{"","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten","Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"},
{"","","Twenty","Thirty", "Forty" ,"Fifty","Sixty","Seventy","Eighty" ,"Ninety"},
{"Hundred"}};
String s = num+"";
String res = "";
if(s.length() == 3){
res += letters[0][Integer.parseInt(s.charAt(0)+"")] +" "+ letters[2][0]+" ";
s = s.substring(1);
num = Integer.parseInt(s);
}
if(num <20){
res +=letters[0][num];
return res.trim();
}else{
res = res +letters[1][Integer.parseInt(s.charAt(0)+"")]+" "+letters[0][Integer.parseInt(s.charAt(1)+"")];
return res.trim();
}
}
另外,搞出来difficulty为hard的题目,还是很有成就感了,美中不足的是效率问题,后来经过多次优化起色不大,到讨论组一看,有一个老外指出来说是substring用的太多,这个方法内部的实现是很耗效率的,据说jdk1.8对此API优化过,jdk7比较慢,找到更高效的方法再更新。。。。。