码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 273: integer to English Words

时间:2017-08-23 15:00:27      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:less   div   mil   nal   stringbu   rto   build   color   english   

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.

LeetCode 273: integer to English Words

标签:less   div   mil   nal   stringbu   rto   build   color   english   

原文地址:http://www.cnblogs.com/shuashuashua/p/7417759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!