程序说明: 输入处理:读取一行输入,分割成单词,并处理最后一个单词的句点。
数字映射:使用哈希表存储数字单词到数字的映射,包括正规和非正规表示。
提取数字:遍历每个单词,转换为小写后查找映射表。若找到,计算平方取模100并格式化为两位数字符串。
排序拼接:对两位数字符串按拼接后的字典序排序(确保最终数值最小),然后拼接所有字符串。
输出结果:去除拼接后字符串的前导零,输出最终结果(若全零则输出0)。
示例测试: 输入:Black Obama is two five zero .
处理:
提取数字:two→2→“04”,five→5→“25”,zero→0→“00”
排序后:[“00”, “04”, “25”]
拼接:“000425” → 去除前导零 → “425”
输出:425
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
#include <unordered_map>
#include <sstream>
using namespace std;
int main() {
string line;
getline(cin, line); // 读取整行输入
stringstream ss(line);
vector<string> words;
string word;
// 分割单词
while (ss >> word) {
words.push_back(word);
}
// 处理最后一个单词的句点
if (!words.empty()) {
string& lastWord = words.back();
if (!lastWord.empty() && lastWord.back() == '.') {
lastWord.pop_back(); // 移除句点
}
}
// 创建数字单词到数字的映射
unordered_map<string, int> mapping = {
{"zero", 0}, {"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}, {"five", 5},
{"six", 6}, {"seven", 7}, {"eight", 8}, {"nine", 9}, {"ten", 10},
{"eleven", 11}, {"twelve", 12}, {"thirteen", 13}, {"fourteen", 14}, {"fifteen", 15},
{"sixteen", 16}, {"seventeen", 17}, {"eighteen", 18}, {"nineteen", 19}, {"twenty", 20},
{"a", 1}, {"both", 2}, {"another", 1}, {"first", 1}, {"second", 2}, {"third", 3}
};
vector<string> digits; // 存储两位数字符串
for (string w : words) {
// 将单词转换为小写
string lowerWord;
for (char c : w) {
lowerWord += tolower(c);
}
// 检查是否为数字单词
if (mapping.count(lowerWord)) {
int num = mapping[lowerWord];
int mod = (num * num) % 100; // 平方后取模100
// 格式化为两位数
char buffer[3];
snprintf(buffer, sizeof(buffer), "%02d", mod);
digits.push_back(string(buffer));
}
}
// 如果没有数字单词,输出0
if (digits.empty()) {
cout << 0 << endl;
return 0;
}
// 自定义排序:按拼接后的字典序排序
sort(digits.begin(), digits.end(), [](const string& a, const string& b) {
return a + b < b + a;
});
// 拼接所有字符串
string combined;
for (const string& s : digits) {
combined += s;
}
// 去除前导零(如果存在)
size_t start = 0;
while (start < combined.size() && combined[start] == '0') {
start++;
}
if (start == combined.size()) {
cout << 0 << endl; // 全为零的情况
} else {
cout << combined.substr(start) << endl; // 输出去除前导零后的结果
}
return 0;
}