题目描述
将非负整数 num 转换为其对应的英文表示。
样例
示例 1:
输入:num = 123
输出:"One Hundred Twenty Three"
示例 2:
输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"
示例 3:
输入:num = 1234567
输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
提示:
0 <= num <= 2^31 - 1
C++ 代码
class Solution {
public:
string small[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string decade[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string big[4] = {"Billion", "Million", "Thousand", ""};
string numberToWords(int num) {
if (!num) return small[0];
string res;
for (int i = 1000000000, j = 0; i > 0; i /= 1000, j ++)
if (num >= i)
{
res += get_part(num / i) + big[j] + ' ';
num %= i;
}
while (res.back() == ' ') res.pop_back();
return res;
}
string get_part(int num)
{
string res;
if (num >= 100)
{
res += small[num / 100] + " Hundred ";
num %= 100;
}
if (!num) return res;
if (num >= 20)
{
res += decade[num / 10] + ' ';
num %= 10;
}
if (!num) return res;
res += small[num] + ' ';
return res;
}
};