273. 整数转换英文表示

题目:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

代码为个人原创,如有雷同,纯属巧合

代码运行结果:

执行用时 :3 ms, 在所有 java 提交中击败了80.62%的用户

内存消耗 :35.7 MB, 在所有 java 提交中击败了80.49%的用户

数字 1,234,567 英文为 One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven

数字   1     英文为 One

数字  234  英文为 Two Hundred Thirty Four

数字  567  英文为 Five Hundred Sixty Seven
 

可见数字翻译成英文格式为:a Billion b Million c Thousand d

其中a, b, c, d都是0-999中的数的英文形式。

所以这道题核心是求出0-999各个数的英文。代码如下:

class Solution {
    
    // 用于储存数字0-19的英文
    private String[] numToWordLT20 = {
        "", "One", "Two", "Three", "Four",
        "Five", "Six", "Seven", "Eight", "Nine",
        "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
        "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
    
    private String[] tem = {"", "Thousand", "Million", "Billion"};
    
    // 0-99的转换
    private String numToWordLT100(int i){
        if(i < 20)
            return numToWordLT20[i];
        
        StringBuilder sb = new StringBuilder();
        switch(i / 10){
            case 2: sb.append("Twenty"); break;
            case 3: sb.append("Thirty"); break;
            case 4: sb.append("Forty"); break;
            case 5: sb.append("Fifty"); break;
            case 6: sb.append("Sixty"); break;
            case 7: sb.append("Seventy"); break;
            case 8: sb.append("Eighty"); break;
            case 9: sb.append("Ninety");
        }
        if(i % 10 != 0){
            sb.append(' ');
            sb.append(numToWordLT20[i % 10]);
        }
        return sb.toString();
    }
    
    // 100-999的转换
    private String numToWordLT1000(int i){
        // 不能保证i一定大于等于100,所以要考虑i < 100位的情况
        if(i < 100)
            return numToWordLT100(i);
        
        StringBuilder sb = new StringBuilder();
        sb.append(numToWordLT20[i / 100]);
        sb.append(" Hundred");
        if(i % 100 != 0){
            sb.append(" ");
            sb.append(numToWordLT100(i % 100));
        }
        return sb.toString();
    }
    
    // 任意数的转换
    public String numberToWords(int num) {
        if(num == 0)
            return "Zero";
        
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 4; i++){
            if(num == 0)
                break;
            if(num % 1000 != 0)
                sb.insert(0, numToWordLT1000(num % 1000) + " " + tem[i] + " ");
            num /= 1000;
        }
        return sb.toString().trim();
    }
}

你可能感兴趣的:(LeetCode,算法,leetcode)