🌕 273. 整数转换英文表示
2022年10月10日
- algorithm
🌕 273. 整数转换英文表示
难度: 🌕
问题描述
解法
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();
}
}