2010上交:计算表达式

题目描述:

对于一个不存在括号的表达式进行计算

输入:

存在多种数据,每组数据一行,表达式不存在空格

输出:

输出结果

样例输入:
6/2+3+3*4
样例输出:
18

#include <iostream>
#include <stack>
using namespace std;
typedef int TYPE;
const int MAXN=1005;
char buf[MAXN];
bool isNum(char ch)
{
    return '0'<=ch&&ch<='9';
}
int priority(char ch)
{
    switch(ch)
    {
        case '+':return 1;
        case '-':return 1;
        case '*':return 2;
        case '/':return 2;
    }
}
TYPE cal(TYPE x,TYPE y,char ch)
{
    switch(ch)
    {
        case '+':return x+y;
        case '-':return x-y;
        case '*':return x*y;
        case '/':return x/y;
    }
}
int main()
{
    while(cin>>buf)
    {
        stack<TYPE> it;
        stack<char> op;
        TYPE e=0;
        for(int i=0;buf[i];i++)
        {
            if(isNum(buf[i]))
            {
                e*=10;
                e+=(buf[i]-'0');
            }
            else
            {
                it.push(e);
                e=0;
                if(op.empty())
                {
                    op.push(buf[i]);
                }
                else
                {
                    char now=buf[i];
                    char ctp=op.top();
                    int np=priority(now);
                    int tp=priority(ctp);
                    if(np>tp)
                    {
                        op.push(now);
                    }
                    else
                    {
                        do
                        {
                            char ch=op.top();op.pop();
                            TYPE y=it.top();it.pop();
                            TYPE x=it.top();it.pop();
                            TYPE z=cal(x,y,ch);
                            it.push(z);
                        }while(!op.empty()&&np<=priority(op.top()));
                        op.push(now);
                    }
                }
            }
        }
        it.push(e);
        while(!op.empty())
        {
            char ch=op.top();op.pop();
            TYPE y=it.top();it.pop();
            TYPE x=it.top();it.pop();
            TYPE z=cal(x,y,ch);
            it.push(z);
        }
        TYPE res=it.top();
        cout<<res<<endl;
    }
    return 0;
}

 简洁代码:

#include <cstdio>
using namespace std;
const int MAXN=1005;
int e[MAXN],top;
int main()
{
    int x;
    char op;
    while(scanf("%d",&x)!=EOF)
    {
        top=0;
        e[top++]=x;
        while(scanf("%c",&op)!=EOF)
        {
            if(op=='\n')    break;
            scanf("%d",&x);
            switch(op)
            {
                case '+':e[top++]=x;break;
                case '-':e[top++]=-x;break;
                case '*':e[top-1]*=x;break;
                case '/':e[top-1]/=x;break;
            }
        }
        int res=0;
        for(int i=0;i<top;i++)
        {
            res+=e[i];
        }
        printf("%d\n",res);
    }
    return 0;
}

 

posted on 2016-04-08 23:24  vCoders  阅读(163)  评论(0)    收藏  举报

导航