View Code of Problem 94

#include<stdio.h>
#include<string.h>
#define MAX 1000000+10
#define Min(a,b) a<b?a:b
char s[MAX];
int stack[MAX];
int n;
char operater(int ch,int start,int e){
    int sum=stack[start];
    for(int i=start+1;i<e;i++){
        switch(ch){
            case '+'-'0':
                sum+=stack[i];
                break;
            case '-'-'0':
                sum-=stack[i];
                break;
            case '*'-'0':
                sum*=stack[i];
                break;
            case '/'-'0':
                sum/=stack[i];
                break;
        }
    }
    //printf("%d\n",sum);
    return sum;
}
int  out(int e){
    int i=e-1;
    while(1){
        if(stack[i]=='('-'0')break;
        i--;
    }
    stack[i]=operater(stack[i+1],i+2,e);
    return i+1;
}
void work(){
    int i=0,flag=0;
    for(int j=0;j<n;j++){
        if(s[j]!=' '){
            if(s[j]=='(')stack[i++]=s[j]-'0';
            else if(s[j]==')')i=out(i);
            else{
                stack[i]=s[j]-'0';
                while(s[j+1]>='0'&&s[j+1]<='9'){
                    j++;
                    stack[i]=stack[i]*10+s[j]-'0';
                }
                i++;
            }
        }
    }
    printf("%d\n",stack[0]);
    return ;
}
int main(){
    while(gets(s)!=NULL){
        n=strlen(s);
        work();
    }
    return 0;
}
/*
(+ 2 (* 3 4) (- 3 5))
12
'('-'0'=-8
'+'-'0'=-5
'*'-'0'=-6
'-'-'0'=
'\'-'0'=
*/

Double click to view unformatted code.


Back to problem 94