🌕 273. 整数转换英文表示

吞佛童子2022年10月10日
  • algorithm
  • Number
大约 1 分钟

🌕 273. 整数转换英文表示

难度: 🌕

问题描述

img_19.png


解法

class Solution {
    String[] singles;
    String[] teens;
    String[] tens;
    String[] block;
    public String numberToWords(int num) {
        // 思路:
        // int 不会超出 22 亿,即 最多 10 的 9 次方 2,147,483,647
        // 可以看出,每 3 位一组,对应的单位分别为 [null, Thousand, Million, Billion]
        // 数字部分,分为 个位数、20以内、100以内、上百 四个区间
        singles = new String[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
        teens = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        tens = new String[] {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        block = new String[] {"", "Thousand", "Million", "Billion"};
        StringBuilder sb = new StringBuilder();
        if(num == 0) {
            return singles[0];
        }
        int index = 0;
        while(num > 0 && index <= 3) {
            int cur = num % 1000;
            StringBuilder tmp = new StringBuilder();
            tmp.append(getStr(cur));
            // System.out.println(tmp.toString() + "  " + tmp.length());
            if(tmp.length() > 0 && index > 0) {
                tmp.append(" ").append(block[index]).append(" ");
            }
            sb.insert(0, tmp);
            num /= 1000;
            index ++;
        }
        if(sb.charAt(sb.length() - 1) == ' ') {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    private String getStr(int cur) {
        StringBuilder sb = new StringBuilder();
        if(cur == 0) {
            return "";
        }
        if(cur >= 100) {
            sb.append(getStr(cur/100)).append(" ").append("Hundred").append(" ");
            cur = cur % 100;
        }
        if(cur >= 20) {
            int index = cur / 10;
            sb.append(tens[index]).append(" ");
            cur = cur % 10;
        }
        if(cur >= 10) {
            int index = cur - 10;
            sb.append(teens[index]).append(" ");
            cur = 0;
        }
        if(cur > 0) {
            sb.append(singles[cur]);
        }
        if(cur == 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}

输出

img_18.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou