题目来源:https://leetcode-cn.com/problems/integer-to-english-words/
大致题意:
给一个 int 范围内的正整数,给出英文表示
思路
因为英文是每三位变一次形容的数量级:thousand、million、billion
所以可以使用递归的方式,每三位进行一次处理,并且根据当前的数量级给处理后的字符串加上对应的单位
递归
首先,可以用字符串数组存下数字对应的字符串:
- 个位数对应的 9 种字符串,0 忽略
- 10 - 19 对应的 10 种字符串
- 20 - 99 每个十位对应的 8 种字符串,以及个位数字对应的字符串(可以对 10 取余后,再从个位数组中取)
- 100 - 999 每个百位对应的 9 种(也就是对应的 9 中个位字符串),然后递归解析后两位
- 三种数量级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);
}
}
}