Algorithm Abstract:
1)Establishing a Look_up Table As A Dictionary with STL map Structure;
2)Get Input And Push Items Into A Stack;
3)Pop Items In The Stack And Compare with items in the dictionary
We locate each number by a Section-Offset Algorithms, when "thousand", “Million” Are received from the stack, the exponent factor were set 3/6, when "hundred" is received, exponent += 2(which is the offset in each 3-digit section)
Caution:
1) Remember to use clear() every time u need to restore the stringstream object
2) eof() returns TRUE when the tail of stream object(sstream,fstream,iostream) is
# include <iostream>
# include <sstream>
# include <map>
# include <stack>
# include <vector>
# include <string>
# include <cmath>
using namespace std;
string loader1[29] =
{"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen"
,"fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","forty","fifty","sixty","seventy","eighty",
"ninety","*"};
int loader2[29] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,30,40,50,60,70,80,90,-1};
map<string,int> Dictionary;
void initializeDic()
{
for ( int i = 0; i < 29; i++ )
{
Dictionary.insert(make_pair(loader1[i],loader2[i]));
}
}
int power10(int f)
{
int result = 0;
double exp = pow(10,(double)f);
result = (int)exp;
return exp;
}
int main()
{
initializeDic();
string inputString;
stringstream s;
string word;
bool flag = false;
int factor = 0;
int sum = 0;
stack<string> numStack;
map<string,int>::iterator itr;
while( getline(cin,inputString) )
{
s.clear();
s.str(inputString);
s.seekg(ios::beg); //Don't Forget This!
factor = 0;
sum = 0;
flag = false;
while ( !s.eof() ) //eof was defined as the tail of the string
{
s >> word;
numStack.push(word);
word.clear();
}
while ( !numStack.empty() )
{
word = numStack.top();
if ( Dictionary.find(word) != Dictionary.end() )
{
itr = Dictionary.find(word);
sum += itr->second * power10(factor);
}
else if ( word == "hundred" )
{
factor += 2;
}
else if ( word == "thousand" )
{
factor = 3;
}
else if ( word == "million" )
{
factor = 6;
}
else if ( word == "negative" )
{
flag = true;
}
numStack.pop();
}
if ( flag )
{
cout << -sum << endl;
}
else
{
cout << sum << endl;
}
}
return 0;
}