题目1010:A + B

来源:互联网 发布:荣誉勋章2010优化 编辑:程序博客网 时间:2024/06/05 03:31
时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:6374

解决:3277

题目描述:
读入两个小于100的正整数A和B,计算A+B.
需要注意的是:A和B的每一位数字由对应的英文单词给出.
输入:
测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B =",相邻两字符串有一个空格间隔.当A和B同时为0时输入结束,相应的结果不要输出.
输出:
对每个测试用例输出1行,即A+B的值.
样例输入:
one + two =three four + five six =zero seven + eight nine =zero + zero =
样例输出:
39096
来源:

2005年浙江大学计算机及软件工程研究生机试真题


【分析】

格式比较固定,中间有两个标识符 ‘+’和 ‘=’,以他们为界来计算出A与B的值,最后根据map的映射关系,直接可以对应出数来,再把A,B相加即可。

但是很多都可以进行优化。

在定义a,b数组的时候列必须要>=6,因为最后还要加以个'\0'

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <fstream>#include <algorithm>#include <map>using namespace std;int main(){    //ifstream cin("aaa.txt");    map<string,int> m ;    char *number[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};    for(int i=0;i<10;i++)        m[number[i]]=i;    string s;    char a[2][6],b[2][6];    while(1)    {        getline(cin,s);        if(s=="zero + zero =")            break;        int i=0,j=0,na=0,nb=0,resulta=0,resultb=0;        while(s[i]!='+')        {            if(s[i]==' ')            {                a[na][j]='\0';                na++;                j=0;            }            else            {                a[na][j++]=s[i];            }            i++;        }        i +=2;        while(s[i]!='=')        {            if(s[i]==' ')            {                b[nb][j]='\0';                nb++;                j=0;            }            else            {                b[nb][j++]=s[i];            }            i++;        }        for(i=0;i<na;i++)            resulta = resulta*10+m[a[i]];        for(i=0;i<nb;i++)            resultb = resultb*10+m[b[i]];        cout<<resulta+resultb<<endl;    }    return 0;}


修改:

对于map根本没有必要,可以用strcmp方法来代替,strcmp两个参数一定要都是字符串才可以。

对于把标志性不变的符号定义成const类型的,养成好习惯。

要学会动态的整合,最好不要全输入之后再去拆开去整合,既耽误时间还使代码复杂。


借鉴几位大神的简洁代码:

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;char strNum[10];const char *equ="=";const char *add="+";char *number[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};int getNum(const char *str){    for(int i=0;i<10;i++)        if(strcmp(str,number[i])==0) return i;    return -1;}int main(){    while(1)    {   //因为cin遇到空格就会结束,一位数一位数的加        int a=0,b=0;        while(scanf("%s",strNum)!=-1&&strcmp(strNum,add)!=0)            a = a*10+getNum(strNum);        while(scanf("%s",strNum)!=-1&&strcmp(strNum,equ)!=0)            b = b*10+getNum(strNum);        if(a==0&&b==0)            break;        cout<<a+b<<endl;    }    return 0;}

0 0
原创粉丝点击