其他分享
首页 > 其他分享> > 力扣 273. 整数转换英文表示

力扣 273. 整数转换英文表示

作者:互联网

题目来源:https://leetcode-cn.com/problems/integer-to-english-words/

大致题意:
给一个 int 范围内的正整数,给出英文表示

思路

因为英文是每三位变一次形容的数量级:thousand、million、billion
所以可以使用递归的方式,每三位进行一次处理,并且根据当前的数量级给处理后的字符串加上对应的单位

递归

首先,可以用字符串数组存下数字对应的字符串:

然后从高到低,每次取三位对数字进行递归

代码:

public class NumberToWords {
    private String[] singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] thousands = {"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        StringBuffer sb = new StringBuffer();
        // 从 billion 到 个位
        for (int i = 3, unit = 1000000000; i >= 0; i--, unit /= 1000) {
            // 当前数量级的 三位数字
            int curNum = num / unit;
            if (curNum != 0) {
                // 减去当前数量级对应的数
                num -= curNum * unit;
                StringBuffer cur = new StringBuffer();
                // 递归
                recursion(cur, curNum);
                // 加上数量级对应的字符串
                cur.append(thousands[i]).append(" ");
                sb.append(cur);
            }
        }
        // 去掉个位尾部加的空格
        return sb.toString().trim();
    }

    public void recursion(StringBuffer curr, int num) {
        if (num == 0) {
            return;
        }
        // 个位
        if (num < 10) {
            curr.append(singles[num]).append(" ");
        } else if (num < 20) {  // 10 - 19
            curr.append(teens[num - 10]).append(" ");
        } else if (num < 100) { // 20 - 99
            curr.append(tens[num / 10]).append(" ");
            recursion(curr, num % 10);
        } else {    // 100 - 999
            curr.append(singles[num / 100]).append(" Hundred ");
            recursion(curr, num % 100);
        }
    }
}

标签:10,num,整数,力扣,273,字符串,curr,对应,append
来源: https://blog.csdn.net/csdn_muxin/article/details/120709134