273 Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
题目中给足了提示,首先告诉我们要3个一组的进行处理,而且题目中限定了输入数字范围为0到2 31  - 1之间,最高只能到billion位,3个一组也只需处理四组即可,那么我们需要些一个处理三个一组数字的函数,我们需要把1到19的英文单词都列出来,放到一个数组里,还要把20,30,... 到90的英文单词列出来放到另一个数组里,然后我们需要用写技巧,比如一个三位数n,百位数表示为n/100,后两位数一起表示为n%100,十位数表示为n%100/10,个位数表示为n%10,然后我们看后两位数是否小于20,小于的话直接从数组中取出单词,如果大于等于20的话,则分别将十位和个位数字的单词从两个数组中取出来。然后再来处理百位上的数字,还要记得加上Hundred。主函数中调用四次这个帮助函数,然后中间要插入"Thousand", "Million", "Billion"到对应的位置,最后check一下末尾是否有空格,把空格都删掉,返回的时候检查下输入是否为0,是的话要返回'Zero'
class Solution {
    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        return helper(num);
    }
    
    private final String[] belowTen = new String[] {"", "One", "Two", "Three", "Four",
                                                    "Five", "Six", "Seven", "Eight", "Nine"};
    private final String[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen",
                                                       "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                                                      "Eighteen", "Nineteen"};
    private final String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty",
                                                       "Sixty", "Seventy", "Eighty", "Ninety"};
    private String helper(int num) {
        String s = new String();
        if (num < 10) {
            s = belowTen[num];
        } else if (num < 20) {
            s = belowTwenty[num - 10];
        } else if (num < 100) {
            s = belowHundred[num / 10] + " " + helper(num % 10);
        } else if (num < 1000) {
            s = helper(num / 100) + " Hundred " + helper(num % 100);
        } else if (num < 1000000) {
            s = helper(num / 1000) + " Thousand " + helper(num % 1000);
        } else if (num < 1000000000) {
            s = helper(num / 1000000) + " Million " + helper(num % 1000000);
        } else {
            s = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
        }
        return s.trim();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值