-
字符串-POJ/UVA 486-English-Number Translator(英语数字转换器)
-
题目链接:5:英语数字转换器
-
思路:
有中文题目不讲大意
这道题会卡人的就是奇葩的英语表示数字大小,外国million下来直接就thousand,所以会出现million和thousand之间隔着个--nine hundred ninty nine ,其实无非就三种情况需要考虑这个问题,遇到million,thousand,hundred,需要回头计算乘上这些表示它们个数的数字,而且也容易发现,thousand 前面的倍数肯定不会比它自己大(因为再大就百万了),hundred也类似
所以取余是一个好东西,只要遇到 million,thousand,hundred 就对前面的计算结果取余,然后前面的结果减掉这部分余数,再加上 million,thousand,hundred乘上这个余数的值
英文数字用多个map储存
我是用多个map,为了表示出优先级,位数越大优先级越高,便于转换
-
代码:
#include<iostream>
#include<sstream>
#include<string>
#include<map>
#include<queue>
using namespace std;
string P1[] = { "zero","one","two","three","four","five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen","fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string P2[] = { "ten","twenty", "thirty", "forty", "fifty","sixty", "seventy", "eighty", "ninety" };
string P3[] = { "hundred", "thousand", "million" };
string Wait_Op_num;
int Mod[] = { 100,100, 10,1000,1000000};
map<string,int> Num_Set[5];
void Pre_Op() //构建map
{
for (int i = 0; i < 20; i++)
Num_Set[0].insert(pair<string, int>(P1[i], i));
for (int i = 1; i < 9; i++)
Num_Set[1].insert(pair<string, int>(P2[i], 10 * (i + 1)));
Num_Set[2].insert(pair<string, int>(P3[0], 100));
Num_Set[3].insert(pair<string, int>(P3[1], 1000));
Num_Set[4].insert(pair<string, int>(P3[2], 1000000));
}
int main()
{
Pre_Op();
while (getline(cin, Wait_Op_num))
{
if (Wait_Op_num.empty())
break;
int Res = 0;
int Privelige = -1;
int Temp_Pre;
int Negative_flag = 0;
stringstream ss(Wait_Op_num); //字符串流
queue<string> Num;
while (!ss.eof())
{
string temp_str;
ss >> temp_str;
//cout << temp_str << endl;
Num.push(temp_str); //单词入队列
}
ss.clear();
while (!Num.empty())
{
int Check_Index = 0;
int Number;
if (Num.front() == "negative") //负数标记
{
Num.pop();
Negative_flag = 1;
}
string Front = Num.front();
Num.pop();
for (Check_Index = 0;; Check_Index++) //对单词进行数值转换
{
auto it = Num_Set[Check_Index].find(Front);
if (it!= Num_Set[Check_Index].end())
{
Number = it->second;
break;
}
}
if (Privelige == -1) //优先级为-1,接触第一个数字
{
Res += Number;
Privelige = Check_Index;
}
else if (Privelige > Check_Index) //当前单词小于最大优先级
{
if (Check_Index >= 2) //遇到 thousand hundred million
{
//one million twenty one thousand one hundred one
int Tail_num = Res % Mod[Check_Index]; //取余
Res -= Tail_num; //减去余数
Res += Tail_num * Number; /加上
}
else
Res += Number; //如果是十位数,个位数 直接加上去
}
else if (Privelige < Check_Index) //当前数优先级高
{
Res *= Number;
Privelige = Check_Index;
}
//cout << Res << endl;
}
if (Negative_flag)
Res *= -1;
cout << Res << endl;
}
return 0;
}
//negative nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine