英语的数字——是多少呢

举个例子, nine hundred and eighty seven million six hundred and fifty four thousand three hundred and twelve,它究竟是多少呢?
这种东西简直不是给人看的,所以呢,咱们想一个算法来翻译它吧。

首先分析一下上面那个数字——嗯,断句先—— nine hundred and eighty seven million | six hundred and fifty four thousand | three hundred and twelve
好了,这下我们算是看懂了——它是 987,654,312
再看一个例子: one hundred million | thirty seven
再看一个例子: one hundred | and two

你发现了什么吗?
好吧,hundred,thousand,million是用来乘的,而其他的是用来加的,对不对?
OK,指点到此结束,送段代码给大家玩玩:

  1. #include<iostream>
  2. #include<sstream>
  3. #include<map>
  4. #include<string>
  5. #include<deque>
  6. using namespace std;
  7. map<string,int> msi;
  8. void init(){
  9.     msi["zero"]=0;
  10.     msi["one"]=1;
  11.     msi["two"]=2;
  12.     msi["three"]=3;
  13.     msi["four"]=4;
  14.     msi["five"]=5;
  15.     msi["six"]=6;
  16.     msi["seven"]=7;
  17.     msi["eight"]=8;
  18.     msi["nine"]=9;
  19.     msi["ten"]=10;
  20.     msi["eleven"]=11;
  21.     msi["twelve"]=12;
  22.     msi["thirteen"]=13;
  23.     msi["fourteen"]=14;
  24.     msi["fifteen"]=15;
  25.     msi["sixteen"]=16;
  26.     msi["seventeen"]=17;
  27.     msi["eighteen"]=18;
  28.     msi["nineteen"]=19;
  29.     
  30.     msi["twenty"]=20;
  31.     msi["thirty"]=30;
  32.     msi["forty"]=40;
  33.     msi["fifty"]=50;
  34.     msi["sixty"]=60;
  35.     msi["seventy"]=70;
  36.     msi["eighty"]=80;
  37.     msi["ninety"]=90;
  38.     
  39.     msi["hundred"]=100;
  40.     msi["thousand"]=1000;
  41.     msi["million"]=1000000;
  42. };
  43. struct _NOTHING_ {_NOTHING_(){init();}} REALLY_NOTHING;
  44. int translate(const string& str){
  45.     istringstream ssin(str);
  46.     string        tmp;
  47.     deque<string> tokens;
  48.     while(ssin>>tmp){
  49.         tokens.push_front(tmp);
  50.     }
  51.     int     x=1;
  52.     int     r=0;
  53.     bool    mul=true;
  54.     for(deque<string>::iterator itr=tokens.begin();itr!=tokens.end();++itr){
  55.         string& S=*itr;
  56.         if(S=="hundred"||S=="thousand"||S=="million"){
  57.             if(mul)
  58.                 x*=msi[S];
  59.             else
  60.                 x=msi[S];
  61.             mul=true;
  62.         }
  63.         else if(S=="and"){
  64.             mul=true;
  65.         }
  66.         else{
  67.             r+=msi[S]*x;
  68.             mul=false;
  69.         }
  70.     }
  71.     return r;
  72. }
  73. int main()
  74. {
  75.     int N;
  76.     for(cin>>N&&cin.get();N--;){
  77.         string strnum;
  78.         getline(cin,strnum);
  79.         cout<<translate(strnum)<<endl;
  80.     }
  81.     return 0;
  82. }
有兴趣的人自己还可以把它扩展一下吧,比如说加入billion(那就不能用int类型表示了哦),加入point,等等
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值