题目地址:
https://leetcode.com/problems/integer-to-english-words/
将一个十进制 32 32 32位非负整数转为其英语表达。
先开个函数专门求一下一个 1 ∼ 999 1\sim 999 1∼999的英文表达,然后对原数拆解为多少个billion,多少个million和多少个thousand,最后拼接起来。代码如下:
class Solution {
public:
vector<string> n0_19 = {"Zero", "One", "Two", "Three",
"Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> n20_90 = {"Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"};
vector<string> n1000 = {" Billion ", " Million ", " Thousand ", ""};
string numberToWords(int num) {
if (num == 0) return "Zero";
string res;
for (int i = 1e9, j = 0; i >= 1; i /= 1000, j++)
if (num >= i) {
res += get(num / i) + n1000[j];
num %= i;
}
if (res.back() == ' ') res.pop_back();
return res;
}
// 得到1~999的英文表示
string get(int x) {
string res;
if (x >= 100) {
res += n0_19[x / 100] + " Hundred ";
x %= 100;
}
if (x >= 20) {
res += n20_90[x / 10 - 2] + ' ';
x %= 10;
if (x != 0) res += n0_19[x];
} else if (x > 0)
// 如果是0的话是不要将“Zero”拼在后面的
res += n0_19[x];
if (res.back() == ' ') res.pop_back();
return res;
}
};
时空复杂度 O ( 1 ) O(1) O(1)。