leetcode 273.Integer to English Words(整数转换英文表示)

将非负整数转换为其对应的英文表示,确保输入小于 2^31 - 1 。

示例 1:

输入: 123 输出: “One Hundred Twenty Three”
示例 2:

输入: 12345 输出: “Twelve Thousand Three Hundred Forty Five”
示例 3:

输入: 1234567 输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

这道题其实很简单,按照英文习惯将数字从低位到高位每三位划分,然后从高位到低位读数,单位分别为Billion Million Thousand;
另外注意一下10-19的读法即可

static String num1[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    static String num2[] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    static String tens[] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    public String numberToWords(int num) {
        if(num == 0){return "Zero";}
        String result = "";
        if(num > 999999999){
            result += numberToWordsWithThreeDIgit(num/1000000000) + " Billion";
            num %= 1000000000;
        }
        if(num > 999999){
            result += numberToWordsWithThreeDIgit(num/1000000) + " Million";
            num %= 1000000;
        }
        if(num > 999){
            result += numberToWordsWithThreeDIgit(num/1000) + " Thousand";
            num %= 1000;
        }
        if(num > 0){
            result += numberToWordsWithThreeDIgit(num);
        }
        return result.trim();
    }

    public String numberToWordsWithThreeDIgit(int num) {
        String result = "";
        if(num > 99){
            result += " " + num1[num / 100 - 1] + " Hundred";
        }
        num %= 100;
        if(num>19){
            result += " " + tens[num / 10 - 2];
            num %= 10;
        }else if(num>9){
            result += " " + num2[num - 10];
            num = 0;
        }
        if(num > 0){
            result += " " + num1[num-1];
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值