首页 > 其他 > 详细

LeetCode 273: integer to English Words

时间:2017-08-23 14:37:01      阅读:258      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!