#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
map<string, int> mapTable;
void initMapTable()
{
mapTable["zero"] = 0;
mapTable["one"] = 1;
mapTable["two"] = 2;
mapTable["three"] = 3;
mapTable["four"] = 4;
mapTable["five"] = 5;
mapTable["six"] = 6;
mapTable["seven"] = 7;
mapTable["eight"] = 8;
mapTable["nine"] = 9;
mapTable["ten"] = 10;
mapTable["eleven"] = 11;
mapTable["twelve"] = 12;
mapTable["thirteen"] = 13;
mapTable["fourteen"] = 14;
mapTable["fifteen"] = 15;
mapTable["sixteen"] = 16;
mapTable["seventeen"] = 17;
mapTable["eighteen"] = 18;
mapTable["nineteen"] = 19;
mapTable["twenty"] = 20;
mapTable["thirty"] = 30;
mapTable["forty"] = 40;
mapTable["fifty"] = 50;
mapTable["sixty"] = 60;
mapTable["seventy"] = 70;
mapTable["eighty"] = 80;
mapTable["hundred"] = 100;
mapTable["thousand"] = 1000;
mapTable["million"] = 1000000;
}
void solve(string& str)
{
string::size_type pos = str.find_first_of(' ');
if (pos == string::npos)
{//只有一个单词
if (str == "negative")
{
cout << "-0" << endl;
}
else if (mapTable.find(str) != mapTable.end())
{
cout << mapTable[str] << endl;
}
}
else
{//至少个单词
string input = str;
int sum = 0,msum = 0,tsum = 0,hsum = 0;
bool bMinus = false;
int count = 0;
string::iterator start = input.begin();
string::iterator end = input.end();
do
{
string word;
end = find(start,input.end(),' ');//找到分隔符
copy(start,end,back_inserter(word));
++count;//单词计数
if (word == "negative")
{
bMinus = true;
}
else
{
if (count == 2 && word == "zero")
{
bMinus = false;
}
int curNum = mapTable[word];
if (curNum == 100)
{
hsum = sum * 100;
sum = 0;
}
else if (curNum == 1000)
{
tsum = (hsum + sum) * 1000;
hsum = 0;
sum = 0;
}
else if (curNum == 1000000)
{
msum = (tsum + hsum + sum) * 1000000;
tsum = 0;
hsum = 0;
sum = 0;
}
else
{
sum += curNum;
}
}
if (end == input.end())
{
if (bMinus)
cout << "-";
cout << msum +tsum + hsum + sum << endl;
break;
}
start = ++end;
} while (end != input.end());
}
}
int main()
{
string str;
initMapTable();
while(getline(cin,str))
{
if (str.length() == 0 || str.length() == 1)
continue;
solve(str);
}
return 0;
}
复制代码
本文转自Phinecos(洞庭散人)博客园博客,原文链接 http://www.cnblogs.com/phinecos/archive/2009/09/12/1565563.html,如需转载请自行联系原作者