273. Integer to English Words

东西都放进去 然后取出来就好了

 

 1 class Solution {
 2     public String numberToWords(int num) {
 3         if(num == 0) return "Zero";
 4         String res = "";
 5         String str = "" + num;
 6         String[] one = new String[]{"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
 7         String[] two = new String[]{"", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
 8         String[] ten = new String[]{"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
 9         String[] three = new String[]{"", "One Hundred ", "Two Hundred ", "Three Hundred ", "Four Hundred ", "Five Hundred ", "Six Hundred ", "Seven Hundred ", "Eight Hundred ", "Nine Hundred "};
10         int count = 0;
11         for(int i = str.length()-1; i >= 0; i = i - 3){
12             StringBuilder sb = new StringBuilder();
13             String sub = str.substring(Math.max(0 , i-2), i+1);
14             int temp = Integer.parseInt(sub);
15             // System.out.println(temp);
16             sb.append(three[temp/100]);
17             temp = temp % 100;
18             if(temp / 10 == 1){
19                 sb.append(ten[temp-10]);
20             }else{
21                  sb.append(two[temp/10]);
22                  temp = temp%10;
23                  sb.append(one[temp]);
24             }
25             if(sb.length() != 0 && count == 0){  //要是这个范围的数字不存在的话就不用加thousan million这些东西
26                 res = sb.toString() + res;
27             }else if(sb.length() != 0 && count == 1){
28                 res = sb.toString() + "Thousand " + res;
29             }else if(sb.length() != 0 && count == 2){
30                 res = sb.toString() + "Million " + res;
31             }else if(sb.length() != 0 && count == 3){
32                 res = sb.toString() + "Billion " + res;
33             }
34             count++;
35             
36         }
37         return res.trim();
38         
39     }
40 }

 

posted @ 2018-10-20 12:44  jasoncool1  阅读(118)  评论(0编辑  收藏  举报