【算法题】Leedcode 273. Integer to English Words 用英文表示数字

37 篇文章 0 订阅
9 篇文章 0 订阅

题目链接:https://leetcode.com/problems/integer-to-english-words/

题目

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 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”

解题思路

注:翻译规律与正常英文格式不同,没有and,0不表示出来。
PS:看到题第一反应是罗马数字和int互相转换的题。

翻译规律有自己的名词表,自然会考虑表驱动;英文中三位一个间隔,分thousand、million、billion、trillion,所以处理的时候也是三位为一个处理单元;题目规定最大为2^31-1,billion就够了。

代码

private String[] numberName = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" ,"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    private String[] tensName = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"};
    private String[] thousandsName = {"","Thousand","Million","Billion","Trillion"};

    public String numberToWords(int num) {
        if(num == 0){
            return "Zero";
        }
        String tmp = num + "";
        String res = "";
        for(int i = 0; i <= (tmp.length() - 1) / 3; i++){
            int startIndex = tmp.length() < (i + 1) * 3 ? 0 : tmp.length() - (i + 1) * 3;
            String toWord = threeToWords(Integer.parseInt(tmp.substring(startIndex, tmp.length() - i * 3)));
            if(toWord.length() != 0){
                res = toWord + " " + thousandsName[i] + " " + res;
            }
        }
        return res.trim();
    }

    private String threeToWords(int num){
        if(num == 0){
            return "";
        }
        String res = "";
        if(num / 100 != 0){
            res = numberName[num / 100] + " Hundred";
        }
        int tmp = num % 100;
        if(tmp < 20){
            res = res + " " + numberName[tmp];
        }else{
            res = res + " " + tensName[tmp / 10] + " " + numberName[tmp % 10];
        }

        return res.trim();
    }

写的时候思路不清,导致代码很乱,调好以后又懒得改,凑合着看吧= =

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值