给定一个整数,打印该整数的英文描述。
示例 1:
输入: 123
输出: “One Hundred Twenty Three”
示例 2:
输入: 12345
输出: “Twelve Thousand Three Hundred Forty Five”
示例 3:
输入: 1234567
输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
示例 4:
输入: 1234567891
输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”
点击此处跳转题目。
由于英文数字表示的特点,将整数每隔 3 位分为一组,从右到左分别对应 “Zero”, “Thousand”, “Million”, “Billion”。因此,现在只需要求解 1 ~ 999 的英文表示,记为 sw(SmallWord)。
因此,所有整数可以表示为:
s w ( B i l l i o n ) ∣ s w ( M i l l i o n ) ∣ s w ( T h o u s a n d ) ∣ s w sw\ (Billion) \ |\ sw \ (Million) \ |\ sw \ (Thousand) \ |\ sw sw (Billion) ∣ sw (Million) ∣ sw (Thousand) ∣ sw
如果 sw 为 “”,其对应括号内的内容不显示。
public class Solution {
private static string[] Words0_9 = {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
};
private static string[] Words10_19 = {
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
};
private static string[] Words_x0 = { // 整十数
"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
};
private static string[] Words_Huge = {
"", "Thousand", "Million", "Billion",
};
private static string Word_100 = "Hundred";
public string NumberToWords(int num) {
if (num == 0) return Words0_9[0];
int cnt = 0;
StringBuilder ans = new StringBuilder();
while (num != 0) {
StringBuilder sw = SmallNumberToWords(num % 1000); // 计算当前组的英文 sw
if (sw.Length != 0) // sw 不为空,则与之前的结果进行拼接
ans = Union(sw, new StringBuilder(Words_Huge[cnt]), ans);
num /= 1000; // num 进入下一组
cnt++;
}
return ans.ToString();
}
// 返回 1 ~ 999 的英文单词
public StringBuilder SmallNumberToWords(int num) {
return num switch {
>= 1000 => new StringBuilder("Wrong"),
>= 100 => Union(new StringBuilder(Words0_9[num / 100]), new StringBuilder(Word_100), SmallNumberToWords(num % 100)),
>= 20 => Union(new StringBuilder(Words_x0[num / 10]), SmallNumberToWords(num % 10)),
>= 10 => new StringBuilder(Words10_19[num - 10]),
_ => new StringBuilder(num > 0 ? Words0_9[num] : "")
};
}
// 拼接字符串
private StringBuilder Union(params StringBuilder[] str) {
StringBuilder ans = str[0];
for (int i = 1; i < str.Length; i++) {
if (str[i].Length == 0) continue; // 如果字符串为空,则直接跳过
if (ans.Length != 0) ans.Append(' '); // 已有的字符不为空,则需要在中间加入一个空格
ans.Append(str[i]);
}
return ans;
}
}