美文网首页
1123.英语数字转换器

1123.英语数字转换器

作者: ShellyWhen | 来源:发表于2017-09-26 00:10 被阅读0次

    题目地址
    描述
    在这个问题中,将用英语给你一个或多个整数。你的任务是将这些数字转换成整型表示。数字范围从-999,999,999到999,999,999.下面是你的程序必须考虑的详尽的英语单词表:
    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
    输入
    输入包括多个样例,注意:
    1.负数前面有词negative
    2.当能用thousand的时候,将不用hundred。例如1500将写为"one thousand five hundred",而不是"fifteen hundred".
    输入将以一个空行结束
    输出
    输出将是每一个单独一行,每一个后面一个换行符

    样例输入
    six
    negative seven hundred twenty nine
    one million one hundred one
    eight hundred fourteen thousand twenty two

    样例输出
    6
    -729
    1000101
    814022

    分析
    million thousand hundred 其实是三个等级,利用递归可将各级数目相加得解,而利用map可以建立英语输入和实际数字的对应关系。
    反思
    大神写这题只用800k,而我写了1300k,实在是化简不了了。花的时间也不短,各种调试。又犯了不少低级错误如局部变量全局变量写两次,循环括号位置错误等等。

    #include<iostream>
    #include<map>
    #include<string>
    #include<vector>
    using namespace std;
    map<string,int> book; 
    string abc[32]={"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"};
    int mindex[3]={1000000,1000,100};
    int num[32]={-1,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,100,1000,1000000};
    vector<int> result;  
    int getn(int i,int j){     //按层次在第i和第j个数中计算和
        int ans=0;
        for(int p=0;p<3;++p){
            for(int k=i;k<=j;++k){
                if (result[k]==mindex[p]){
                    ans+=getn(i,k-1)*mindex[p];
                    i=k+1;
                    break;
                }
            }
        }
        for(;i<=j;++i)ans+=result[i];
        return ans; 
    }
    int main(){
        for(int i=0;i<32;++i)
            book.insert(make_pair(abc[i],num[i]));
        while(1){
            bool flag=0;
            string s;
            getline(cin,s);     //直接输入字符串的函数getline()
            int len=s.size();
            if(len==0)break;
            int i=0,ans=0;
                for(int j=1;j<=len;++j)
                    if(s[j]==' '||j==len){
                        result.push_back(book[s.substr(i,j-i)]);
                        i=j+1;
                        j+=2;
                    }   
            if(result[0]==-1){
                flag=1;
                result.erase(result.begin(),result.begin()+1);
                --len;
            }
            if(flag)cout<<'-';
            cout<<getn(0,result.size()-1)<<endl;
            result.clear();
        }
    }
    

    相关文章

      网友评论

          本文标题:1123.英语数字转换器

          本文链接:https://www.haomeiwen.com/subject/pdyjextx.html