Cod sursa(job #2191309)

Utilizator DawlauAndrei Blahovici Dawlau Data 2 aprilie 2018 15:06:50
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include<fstream>
#include<string>
#include<stack>
using namespace std;

ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

string String;
stack<char> ops;
stack<int> nums;
int StrLen;

inline int getNum(int idx){

    int no = 0;
    while(isdigit(String[idx]))
        no = no * 10 + String[idx++] - '0';
    nums.push(no);
    return idx - 1;
}

inline void solve(){

    char op = ops.top();
    ops.pop();

    int a = nums.top();
    nums.pop();
    int b = nums.top();
    nums.pop();

    if(op == '+') nums.push(a + b);
    else if(op == '-') nums.push(b - a);
    else if(op == '*') nums.push(a * b);
    else nums.push(b / a);
}

inline int opPriority(char operation){

    if(operation == '+' or operation == '-') return 1;
    if(operation == '*' or operation == '/') return 2;
    return 0;
}

int main(){

    fin >> String;
    StrLen = String.size();

    int idx;
    for(idx = 0; idx < StrLen; ++idx)
        if(String[idx] == '(')
            ops.push(String[idx]);
        else{

            if(isdigit(String[idx]))
                idx = getNum(idx);
            else if(String[idx] == ')'){

                while(ops.top() != '(')
                    solve();
                ops.pop(); /// pop the '('
            }
            else{ ///operations time

                int priot = opPriority(String[idx]);
                while(!ops.empty() and opPriority(ops.top()) >= priot)
                    solve();
                ops.push(String[idx]);
            }
        }
    while(!ops.empty())
        solve();
    fout << nums.top();
}