LeetCode Integer to English Words(整數轉化為英文字母)
阿新 • • 發佈:2019-02-07
題意:給出一下正整數,輸出英文表示
思路:每三個數一組,因為最多有三組,對應的分別為Billion,Million,Thousand。然後針對每組的數輸出
程式碼如下:
public class Solution { private String[] bigNum = {"Billion", "Million", "Thousand","" }; private String[] num_str = {"", "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"}; private String numberToString(int num) { StringBuilder sb = new StringBuilder(); int n = num / 100; if (n > 0) { sb.append(num_str[n]); sb.append(" Hundred"); } n = num % 100; if (n > 0 && n < 20) { if (sb.length() != 0) sb.append(" "); sb.append(num_str[n]); } else if (n >= 20) { if (sb.length() != 0) sb.append(" "); sb.append(num_str[19 + n / 10 - 1]); n %= 10; if (n != 0) { if (sb.length() != 0) sb.append(" "); sb.append(num_str[n]); } } return sb.toString(); } public String numberToWords(int num) { List<Integer> ar = new ArrayList<Integer>(); while (num >= 1000) { int tmp = num % 1000; ar.add(tmp); num /= 1000; } if (num != 0) ar.add(num); //System.out.println(ar); int size = ar.size(); //System.out.println("size:" + size); StringBuilder sb = new StringBuilder(); for (int i = size - 1; i >= 0; i--) { if (ar.get(i) != 0) { if (sb.length() != 0) sb.append(" "); sb.append(numberToString(ar.get(i))); if (!bigNum[3 - i].isEmpty()) sb.append(" "); sb.append(bigNum[3 - i]); } } if (sb.length() == 0) sb.append("Zero"); return sb.toString(); } }