In this problem, you will be given one or more integers in English. Your task is to translate these numbers into their integer representation. The numbers can range from negative 999,999,999 to positive 999,999,999. The following is an exhaustive list of English words that your program must account for:
negative, 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, hundred, thousand, million InputThe input consists of several instances. Notes on input:
Negative numbers will be preceded by the word negative.
The word "hundred" is not used when "thousand" could be. For example, 1500 is written "one thousand five hundred", not "fifteen hundred".
The input is terminated by an empty line.
OutputThe answers are expected to be on separate lines with a newline after each.
Sample Inputsix negative seven hundred twenty nine one million one hundred one eight hundred fourteen thousand twenty two
Sample Output6 -729 1000101 814022
#include<iostream> #include <cstring> #include <string> #include <algorithm> #include <map> #include <sstream> using namespace std; int main(){ map<string, int> m; m["zero"] = 0; m["one"] = 1; m["two"] = 2; m["three"] = 3; m["four"] = 4; m["five"] = 5; m["six"] = 6; m["seven"] = 7; m["eight"] = 8; m["nine"] = 9; m["ten"] = 10; m["eleven"] = 11; m["twelve"] = 12; m["thirteen"] = 13; m["fourteen"] = 14; m["fifteen"] = 15; m["sixteen"] = 16; m["seventeen"] = 17; m["eighteen"] = 18; m["nineteen"] = 19; m["twenty"] = 20; m["thirty"] = 30; m["forty"] = 40; m["fifty"] = 50; m["sixty"] = 60; m["seventy"] = 70; m["eighty"] = 80; m["ninety"] = 90; string s1,s; while(getline(cin,s1) && s1!=""){ istringstream is(s1); int gs = 0,b = 0,q = 0,bw = 0; //个十/百/千/百万 bool flag = 0; while(is>>s){ if(s == "hundred"){ b = gs*100; gs = 0; } else if(s == "thousand"){ q = (gs+b)*1000; gs = 0; b = 0; } else if(s == "million"){ bw = (gs + b + q)*1000000; gs = 0; b = 0; q = 0; } else if(s == "negative") flag = 1; else gs += m[s]; } if(flag) cout<<"-"<<gs+b+q+bw<<endl; else cout<<gs+b+q+bw<<endl; } return 0; }
四个位置填一遍算一遍,每遍以出现量词结束,最后一遍可能没有量词,自己意会下。