題目
將非負整數轉換爲其對應的英文表示。可以保證給定輸入小於 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"
示例 4:
輸入: 1234567891
輸出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
解法
class Solution {
public String numberToWords(int num) {
if(num == 0){
return "Zero";
}
StringBuilder b = new StringBuilder();
String str = String.valueOf(num);
if(str.length() > 9){
b.append(toEnglish(str.substring(0,str.length()-9))).append("Billion ");
str = str.substring(str.length()-9);
}
if(str.length() > 6){
String s = toEnglish(str.substring(0,str.length()-6));
if(!s.trim().equals("")){
b.append(s).append("Million ");
}
str = str.substring(str.length()-6);
}
if(str.length() > 3){
String s = toEnglish(str.substring(0,str.length()-3));
if(!s.trim().equals("")){
b.append(s).append("Thousand ");
}
str = str.substring(str.length()-3);
}
b.append(toEnglish(str));
String res = b.toString().trim();
while(res.contains(" ")){
res = res.replace(" "," ");
}
return res;
}
private String toEnglish(String str){
StringBuilder b = new StringBuilder();
if(str.length()>2){
char c = str.charAt(str.length()-3);
if(c!='0'){
b.append(getNum(c)).append(" Hundred ");
}
}
boolean flag = true;
if(str.length()>1){
char c = str.charAt(str.length()-2);
if(c!='0'){
if(c=='1'){
flag = false;
b.append(getNumteen(str.charAt(str.length()-1))).append(" ");
}else{
b.append(getNumty(c)).append(" ");
}
}
}
if(str.length()>0 && flag){
char c = str.charAt(str.length()-1);
b.append(getNum(c)).append(" ");
}
return b.toString();
}
private String getNum(char c){
switch(c){
case '0':
return "";
case '1':
return "One";
case '2':
return "Two";
case '3':
return "Three";
case '4':
return "Four";
case '5':
return "Five";
case '6':
return "Six";
case '7':
return "Seven";
case '8':
return "Eight";
case '9':
return "Nine";
default:
return "";
}
}
private String getNumty(char c){
switch(c){
case '2':
return "Twenty";
case '3':
return "Thirty";
case '4':
return "Forty";
case '5':
return "Fifty";
case '6':
return "Sixty";
case '7':
return "Seventy";
case '8':
return "Eighty";
case '9':
return "Ninety";
default:
return "";
}
}
private String getNumteen(char c){
switch(c){
case '0':
return "Ten";
case '1':
return "Eleven";
case '2':
return "Twelve";
case '3':
return "Thirteen";
case '4':
return "Fourteen";
case '5':
return "Fifteen";
case '6':
return "Sixteen";
case '7':
return "Seventeen";
case '8':
return "Eighteen";
case '9':
return "Nineteen";
default:
return "";
}
}
}