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"

 

令人烦躁的一个题。要注意的是,101在本题是"One Hundred One"而不是"One Hundred and One",这样反而简单很多。我不觉得这道题有什么实际的算法考量下的“意义”。写起来又费时间,也没什么值得思考的点。无非就是按照西方读数方式,每三位数一读。每读三位数的时候在三位数后面加上单位(Thousand, Million, or Billion)即可。其中的corner case是当读取的三位数是“0”,那么后面的单位就要舍弃。比如1000000,读第二个三位数是“000”,那么对应的单位Thousand是要舍弃的,否则就会变成One Million Thousand的错误结果。详见代码吧。

 


Java

class Solution {
    //全局变量先把要用的英文存起来
    String[] units = {"", " Thousand", " Million", " Billion"};
    String[] num0To9 = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    String[] num10To19 = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] num10To90 = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
    public String numberToWords(int num) {
        if (num == 0) return "Zero";
        String res = "";   
        int count = 0; //记录当前三位数下后面跟的单位
        while (num > 0) {
            String temp = "";
            temp = units[count]; //记录当前三位数下后面跟的单位
            int cur = num % 1000; //每三位一读,从后往前
            String pre = convert(cur); //转化当前数字最后的三位数
            if (pre == "") temp = ""; //如果是"000",那么就等于什么都没发生,舍弃单位
            else temp = convert(cur) + temp; //否则结合结果和单位
            if (res.length() != 0 && res.charAt(0) != ' ') //处理一下加上单位的空格情况
                res = temp + " " + res;
            else res = temp + res;
            num = (num - num % 1000) / 1000; //处理往前三位数
            count++;
        }
        return res;
    }
    //转化任意三位数
    public String convert(int num) {
        if (num == 0) return "";
        if (num < 10)
            return num0To9[num];
        else if (num >= 10 && num <= 19) 
            return num10To19[num - 10];
        else if (num >= 20 && num <= 99) {
            if (num % 10 == 0) return num10To90[num / 10 - 1];
            else {
                String s1 = num0To9[num%10];
                String s2 = num10To90[num/10 - 1];
                return s2 + " " + s1;
            }
        }
        else {
            if (num % 100 == 0)
                return num0To9[num / 100] + " Hundred";
            else {
                String temp = convert(num % 100);
                return convert(num - num % 100) + " " + temp;
            }
        }    
    }
}

 

posted on 2018-08-09 12:40  小T在学习  阅读(712)  评论(0编辑  收藏  举报