Try Again

简单加减乘除法四则运算表达式的求解

  今天看见一道放了好久的题,以前怕麻烦一直搁在一边,今天仔细想了一下,终于弄懂了,加减乘除法四则运算表达式,主要考虑优先级,从后往前考虑。具体可参考http://www.nowamagic.net/librarys/veda/detail/2307

 求9+(3-1)*3+10/2

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <cassert>
#include <ctime>
#include <map>
#include <set>
using namespace std;
#pragma comment(linker, "/stck:1024000000,1024000000")
#define lowbit(x) (x&(-x))
#define max(x,y) (x>=y?x:y)
#define min(x,y) (x<=y?x:y)
#define MAX 100000000000000000
#define MOD 1000
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.1415926535897932384626433832
#define ios() ios::sync_with_stdio(true)
#define inf 0x3f3f3f3f
#define mem(a) (memset(a,0,sizeof(a)))
stack<char>ch;
stack<int>num;
char s[105];
int k=0;
bool flag=false;
void solveadd()
{
    int front,last;
    char vis;
    while(ch.top()!='(')
    {
        last=num.top();
        num.pop();
        front=num.top();
        num.pop();
        vis=ch.top();
        ch.pop();
        switch(vis)
        {
            case '+':front+=last;break;
            case '-':front-=last;break;
            case '*':front*=last;break;
            case '/':front/=last;break;
        }
        num.push(front);
    }
}
void solvemul()
{
    int front,last;
    char vis;
    while(ch.top()=='*' || ch.top()=='/')
    {
        last=num.top();
        num.pop();
        front=num.top();
        num.pop();
        vis=ch.top();
        ch.pop();
        if(vis=='*') front*=last;
        else front/=last;
        num.push(front);
    }
}
int main()
{
    scanf("%s",s);
    ch.push('(');
    strcat(s,"@");
    for(int i=0;s[i];i++)
    {
        if(s[i]>='0' && s[i]<='9')
        {
            k=k*10+(int)(s[i]-'0');
            flag=true;
            continue;
        }
        if(flag){
            num.push(k);
            k=0;
            flag=false;
        }
        switch(s[i])
        {
            case '(':ch.push('(');break;
            case ')':solveadd();ch.pop();break;
            case '+':solveadd();ch.push('+') ;break;
            case '-':solveadd();ch.push('-');break;
            case '*':solvemul();ch.push('*');break;
            case '/':solvemul();ch.push('/');break;
            case '@':solveadd();break;
        }
    }
    solveadd();
    printf("%d\n",num.top());
    return 0;
}

 

 

 

posted @ 2018-03-12 21:17  十年换你一句好久不见  阅读(1852)  评论(0编辑  收藏  举报