ได้รับจำนวนเต็มบวก แปลงเป็นคำอ่านภาษาอังกฤษ รองรับถึง 1 พันล้าน (Billion) เช่น 56 → "Fifty-Six"
ตัวอย่าง
Input: 5678
Output: Five Thousand Six Hundred Seventy Eight
อัลกอริทึม: Recursive Lookup Table
- ตาราง
numbers: vector of pairเรียงจากใหญ่ไปเล็ก (Billion, Million, Thousand, Hundred, Ninety, ..., One) solve(input)แบบ recursive:- ถ้า input = 0 → "Zero"
- วนหา entry แรกที่
value ≤ input:- ถ้า value ≥ 100 (Billion, Million, Thousand, Hundred):
result = solve(input/value) + " " + nameถ้าเหลือเศษ →+ " " + solve(remainder) - ถ้า value < 100:
result = name + (input > value ? " " + solve(input-value) : "") - break
- ถ้า value ≥ 100 (Billion, Million, Thousand, Hundred):
- คืน result
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
vector<pair<string, int>> numbers{
{"Billion", 1000000000}, {"Million", 1000000}, {"Thousand", 1000}, {"Hundred", 100},
{"Ninety", 90}, {"Eighty", 80}, {"Seventy", 70}, {"Sixty", 60}, {"Fifty", 50},
{"Forty", 40}, {"Thirty", 30}, {"Twenty", 20}, {"Nineteen", 19}, {"Eighteen", 18},
{"Seventeen", 17}, {"Sixteen", 16}, {"Fifteen", 15}, {"Fourteen", 14}, {"Thirteen", 13},
{"Twelve", 12}, {"Eleven", 11}, {"Ten", 10}, {"Nine", 9}, {"Eight", 8}, {"Seven", 7},
{"Six", 6}, {"Five", 5}, {"Four", 4}, {"Three", 3}, {"Two", 2}, {"One", 1}
};
string solve(int input) {
if (input == 0) return "Zero";
string result;
for (auto& num : numbers) {
if (num.second <= input) {
if (num.second >= 100) {
result = solve(input / num.second) + " " + num.first;
if (input > (input / num.second) * num.second)
result += " " + solve(input - (input / num.second) * num.second);
} else {
result = num.first + (input > num.second ? " " + solve(input - num.second) : "");
}
break;
}
}
return result;
}
int main() {
cout << solve(5678) << endl;
return 0;
}
Input
5678
Output
Five Thousand Six Hundred Seventy Eight