题目链接:https://leetcode.cn/problems/english-int-lcci/description/
题目大意:给出一个数字num
,输出它的英文表达。
思路:需要一些前置知识,否则无法下手。在英文表达中,是将数字分为三个三个一组来表达的,从低到高位的最大单位分别是Billion, Million, Thousand
(在题目给定的数字范围内),身下的就是三位数字内部的处理了,显然就是Hundred
再加上“几十几”。所以可以递归处理(实际上也就递归一层)。
完整代码
class Solution {
public:
string Digits[10] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string Teens[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string Tens[10] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string Thousands[10] = {"", "Thousand", "Million", "Billion"};
void DFS(string& s, int cur) {
if (cur == 0)
return;
if (cur < 10)
s += Digits[cur] + " ";
else if (cur < 20)
s += Teens[cur % 10] + " ";
else if (cur < 100) {
s += Tens[cur / 10] + " ";
DFS(s, cur%10);
}
else {
s += Digits[cur / 100] + " " + "Hundred ";
DFS(s, cur % 100);
}
}
string numberToWords(int num) {
if (num == 0)
return "Zero";
string ans;
int unit = 1e9;
for (int i = 3; i >=0; i--) {
int cur = num / unit;
if (cur) {
num %= unit;
string str;
DFS(str, cur);
ans += str + Thousands[i] + " ";
}
unit /= 1000;
}
while (ans.back() == ' ')
ans.pop_back();
return ans;
}
};