[LeetCode]Integer to English Words

之前写了个很复杂的办法,后来参考网上思路,觉得这个是最简便的写法了

public class Solution {
    public String numberToWords(int num) {
        String[] first = "Zero One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen".split(" ");
        String[] second = "Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split(" ");
        String[] third = "Hundred Thousand Million Billion".split(" ");
        String result = "";
        if (num < 20) {
            return first[num];
        } else if (num < 100) {
            result = second[num / 10 - 2];
            result += num % 10 == 0 ? "" : " " + first[num % 10];
        } else if (num < 1000) {
            result = first[num / 100] + " " + third[0];
            String tmp = numberToWords(num % 100).equals("Zero") ? "" : numberToWords(num % 100);
            if (tmp != "")
                result = result + " " + tmp;
        } else  if (num < 1000000) {
            result = numberToWords(num / 1000) + " " + third[1];
            String tmp = numberToWords(num % 1000).equals("Zero") ? "" : numberToWords(num % 1000);
            if (tmp != "")
                result = result + " " + tmp;
        } else if (num < 1000000000) {
            result = numberToWords(num / 1000000) + " " + third[2];
            String tmp = numberToWords(num % 1000000).equals("Zero") ? "" : numberToWords(num % 1000000);
            if (tmp != "")
                result = result + " " + tmp;
        } else {
             result = numberToWords(num / 1000000000) + " " + third[3];
             String tmp = numberToWords(num % 1000000000).equals("Zero") ? "" : numberToWords(num % 1000000000);
             if (tmp != "")
                result = result + " " + tmp;        
        }
        return result;
    }
}

 

posted @ 2015-12-02 11:42  Weizheng_Love_Coding  阅读(146)  评论(0编辑  收藏  举报