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"

题意:将支票上的阿拉伯数字写成英文单词

代码

class Solution {

    // 首先定义可能出现的 english words 

    String[] lessThan20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    String[] thousands = {"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";   
        }
        String result = ""; // 比如 12345
        int i = 0;
        while (num > 0) {  //<1>
            if (num % 1000 != 0) {  // <2>
                result = helper(num % 1000) + thousands[i] + " " + result;  //  <3>递归调用 helper(num % 1000) // <13>返回 "Three"+ " Hundred " + "Forty" + "Five" //  <16> 调用helper(12) 返回"Twelve" + thousands[1] + "Three"+ " Hundred " + "Forty" + "Five"
            }
            num /= 1000; // <14> num = 12
            i++; // <15> i = 1
        }
        return result.trim();//<17> trim()去掉String字符串的首尾空格
    }

    private String helper(int num) {//<4>递归调用 helper(345) // <7>递归调用 helper(45)// <9>递归调用 helper(5)
        if (num == 0) {
            return "";
        } else if (num < 20) { 
            return lessThan20[num] + " "; //  <10> 处理 <9>,返回 "Five"
        } else if (num < 100) {
            return tens[num / 10] + " " + helper(num % 10); // <8>递归调用 helper()  //  <11>处理 <7>,返回  "Forty" + "Five"
        } else { //  <5>
            return lessThan20[num / 100] + " Hundred " + helper(num % 100); // <6>递归调用 helper(45) // <12>处理 <4>返回 "Three"+ " Hundred " + "Forty" + "Five"
        }
    }
}

results matching ""

    No results matching ""