JAVA练习216-整数的英语表示

给定一个整数,打印该整数的英文描述。

示例 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"

示例 4:
输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

分析:

方法:分治算法

英语的表示和汉语不同,它是隔着三位数表示,比如 "Thousand", "Million", "Billion",因此我们只需要将数字按三位分别进行添加英文即可,因为整形最大为 2147483647,刚好最高位就在 Billion 上,如果数字刚好在该位上,直接判断即可。我们可以将个位,十位,千位分别创建数组方便操作。

时间复杂度:O(1)        取决于数字的位数
空间复杂度:O(1)

class Solution {

    //英文
    private static String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private static String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private static String[] trous = {"Thousand", "Million", "Billion"};
    private static int[] nums = {1000, 1000000, 1000000000};

    public String numberToWords(int num) {
        //0
        if(num == 0){
            return "Zero";
        }
        //结果
        StringBuilder sb = new StringBuilder();
        //1000 000 000
        if(num / nums[2] > 0){
            sb.append(ones[num / nums[2]]);
            sb.append(" ").append(trous[2]);
            num %= nums[2];
        }
        //1000 000
        if(num / nums[1] > 0){
            translate(num / nums[1], sb);
            sb.append(" ").append(trous[1]);
            num %= nums[1];
        }
        //1000
        if(num / nums[0] > 0){
            translate(num / nums[0], sb);
            sb.append(" ").append(trous[0]);
            num %= nums[0];
        }
        translate(num, sb);
        return sb.toString().trim();
    }

    //对一个千位数进行翻译
    public void translate(int num, StringBuilder sb){
        //百位
        if(num / 100 > 0){
            sb.append(" ").append(ones[num / 100]).append(" ").append("Hundred");
            num %= 100;
        }
        //十位
        if(num / 10 > 1){
            sb.append(" ").append(tens[num / 10]);
            num %= 10;
        }
        //个位
        if(num > 0){
            sb.append(" ").append(ones[num]);
        }
    }
}

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/english-int-lcci

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值