將非負整數(< 2³¹)轉換為英文單詞表示。例如:
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
convertHundreds(num) 處理 0~999 的數字:num/100 + "Hundred"class Solution {
public:
string numberToWords(int num) {
if (num == 0) return "Zero";
const vector units = {"", " Thousand", " Million", " Billion"};
string res;
for (int i = 0; num > 0; ++i) {
if (num % 1000 != 0) {
res = convertHundreds(num % 1000) + units[i] + res;
}
num /= 1000;
}
return res.substr(1); // 去除首部空格
}
private:
string convertHundreds(int num) {
static const vector below20 = {"", " One", " Two", " Three", " Four", " Five",
" Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen",
" Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen"};
static const vector tens = {"", "", " Twenty", " Thirty", " Forty", " Fifty",
" Sixty", " Seventy", " Eighty", " Ninety"};
string s;
if (num >= 100) {
s += below20[num/100] + " Hundred";
num %= 100;
}
if (num >= 20) {
s += tens[num/10];
num %= 10;
}
if (num > 0) s += below20[num];
return s;
}
};