TJ
2026-04-18 21:03:01
发布于:浙江
23阅读
0回复
0点赞
这道题要求将英文数字写法转换为阿拉伯数字。
题目理解
- 输入是英文数字描述,包含可能的
negative表示负数。 - 数字范围
-999,999,999到999,999,999。 - 用到的单词是标准的 0–19、20–90(整十)、hundred、thousand、million。
- 没有
and,例如103写作one hundred three。 - 规则符合英语习惯,比如
1500是one thousand five hundred而不是fifteen hundred。
思路
- 将输入按空格分割成单词列表。
- 处理
negative标记。 - 依次处理数字,规则如下:
- 遇到
one到nineteen→ 当前值为 1–19 - 遇到
twenty到ninety→ 当前值为 20–90 - 遇到
hundred→ 当前部分 ×100 - 遇到
thousand→ 当前累计值 ×1000 并加到总结果中,重置当前部分 - 遇到
million→ 当前累计值 ×1,000,000 并加到总结果中,重置当前部分 - 处理末尾的当前部分加入总结果
- 遇到
示例
negative seven hundred twenty nine
negative→ 标记为负seven→ cur = 7hundred→ cur = 7 × 100 = 700twenty→ cur = 700 + 20 = 720nine→ cur = 720 + 9 = 729- 结束,
total = cur = 729 - 输出
-729
实现代码
#include <bits/stdc++.h>
#define ll long long
using namespace std;
map<string, int> w = {
{"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}, {"thirty", 30},
{"forty", 40}, {"fifty", 50}, {"sixty", 60}, {"seventy", 70},
{"eighty", 80}, {"ninety", 90}
};
ll ans = 0;
ll cur = 0; // 当前处理部分(小于1000)
bool neg = false;
int main() {
string s, t;
getline(cin, s);
stringstream ss(s);
while (ss >> t) {
if (t == "negative") {
neg = true;
} else if (t == "hundred") {
cur *= 100;
} else if (t == "thousand") {
ans += cur * 1000;
cur = 0;
} else if (t == "million") {
ans += cur * 1000000;
cur = 0;
} else {
cur += w[t];
}
}
ans += cur;
if (neg) ans = -ans;
cout << ans;
return 0;
}
复杂度
- 时间:O(n),n 为单词数量
- 空间:O(1)(除了单词表固定)
说明
这个解法直接模拟了英语数字的解析过程,按照 hundred、thousand、million 做乘法和加法,注意要按顺序处理,先加个位十位,遇到 hundred 乘,遇到 thousand/million 累加到总和中再重置。
这里空空如也







有帮助,赞一个