题目链接
整数的英语表示
题目描述
注意点
- 0 <= num <= 2^31 - 1
解答思路
- 每三个数字形成一组(高位不足的部分可以用0填充),使用StringBuilder拼接每组的数字和单位
- 关键是三个数字的英语表示,包含个位、十位、百位,找到三个数字值为0、[1, 9]、[10, 19]、[20, 99]、[100, 999]用英语表示的规律
- 可以先将[1, 9]、[10, 19]、[20, 99]以及单位存储到数组中,方便根据每一位的数字快速找到其英语表示,[100, 999]则是由单个数字 + “Hundred” + 十位/个位/无组成
代码
class Solution {
String[] singles = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
String[] teens = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
String[] tens = {"", "Ten ", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
String[] thousands = {"", "Thousand ", "Million ", "Billion "};
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
StringBuilder res = new StringBuilder();
String sNum = num + "";
int remainder = sNum.length() % 3;
String s = "";
if (remainder == 1) {
s = "00";
}
if (remainder == 2) {
s = "0";
}
s = s + num;
int n = s.length();
int unit = n / 3 - 1;
for (int i = 0; i < n; i += 3) {
String tmp = buildWords(s, i);
if (!"".equals(tmp)) {
res.append(tmp);
res.append(thousands[unit]);
}
unit--;
}
res.deleteCharAt(res.length() - 1);
return res.toString();
}
public String buildWords(String s, int i) {
StringBuilder sb = new StringBuilder();
if (s.charAt(i) != '0') {
sb.append(singles[s.charAt(i) - '0']);
sb.append("Hundred").append(" ");
}
switch(s.charAt(i + 1)) {
case '0':
sb.append(singles[s.charAt(i + 2) - '0']);
break;
case '1':
sb.append(teens[s.charAt(i + 2) - '0']);
break;
default:
sb.append(tens[s.charAt(i + 1) - '0']);
sb.append(singles[s.charAt(i + 2) - '0']);
break;
}
return sb.toString();
}
}
关键点
- 三个数字组成的一组整数怎么用英语表示
- 注意每个单词后面的空格以及最后一个单词后没有空格