Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
string numberToWords(int num) {
if (!num) {
return "Zero";
}
string res;
for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) {
if (num >= i) {
res += getPart(num / i) + big[j] + ' ';
num %= i;
}
}
while (res.back() == ' ') {
res.pop_back();
}
return res;
}
string getPart(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;
}
private:
const vector<string> big{"Billion", "Million", "Thousand", ""};
const vector<string> small{"", "One", "Two", "Three",
"Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"};
const vector<string> decade{"", "Ten", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
};