用C++用单词表示正整数的程序
假设我们得到一个正整数。我们必须用单词拼写数字;就像如果输入数字“56”,输出将是“56”。转换范围高达十亿。
所以,如果输入像input=5678,那么输出就是五千六百七十八。
示例
让我们看看以下实现以获得更好的理解-
#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; }
输入
5678输出结果
Five Thousand Six Hundred Seventy Eight