一、题目
给定一个整数,打印该整数的英文描述。
示例 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”
点击此处跳转题目。
二、C# 题解
由于英文数字表示的特点,将整数每隔 3 位分为一组,从右到左分别对应 “Zero”, “Thousand”, “Million”, “Billion”。因此,现在只需要求解 1 ~ 999 的英文表示,记为 sw(SmallWord)。
- 1 - 20:特殊部分,无规律。
- 100 以内整十:特殊部分,无规律。
- 非整十二位数:整十部分 + 个位数。
- 100 - 999:整百部分 + 二位数。
因此,所有整数可以表示为:
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文章来源:https://www.toymoban.com/news/detail-735286.html
如果 sw 为 “”,其对应括号内的内容不显示。文章来源地址https://www.toymoban.com/news/detail-735286.html
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;
}
}
- 时间:60 ms,击败 100.00% 使用 C# 的用户
- 内存:36.24 MB,击败 100.00% 使用 C# 的用户
到了这里,关于LeetCode 面试题 16.08. 整数的英语表示的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!