class Solution {
   private final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private final String[] THOUSANDS = {"", "Thousand ", "Million ", "Billion "};
    

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (num > 0) { 
            if (num % 1000 != 0) {
                result.insert(0, THOUSANDS[i]);
                getString(num % 1000, result);
            }
            i++;
            num /= 1000;
        }
        return result.toString().trim();
    }
    
    private void getString(int num, StringBuilder result) {
        if (num == 0) {
            return;
        } else if (num < 20) {
            result.insert(0, " ");
            result.insert(0, LESS_THAN_20[num]);
        } else if (num < 100) {
            getString(num % 10, result);
            result.insert(0, " ");
            result.insert(0, TENS[num / 10]);
        } else {
            getString(num % 100, result);
            result.insert(0, " Hundred ");
            result.insert(0, LESS_THAN_20[num / 100]);
        }
    }
}

 

 

1. Need check whether each loop of 1000 is 0 or not. Otherwise, it will introduce extra "thousands" words.

2. Each loop needs to count the how many thousands have been processed.

3. Better to use StringBuilder.

posted on 2017-08-23 13:38  keepshuatishuati  阅读(125)  评论(0编辑  收藏  举报