Cod sursa(job #2676119)

Utilizator Iustin01Isciuc Iustin - Constantin Iustin01 Data 23 noiembrie 2020 16:11:13
Problema Evaluarea unei expresii Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>
using namespace std;

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

string s;
stack < char > st;
stack < int > n;
int nr;

int priority(char ch){
    if(ch == '+' || ch == '-')
        return 2;
    return 1;
}

int oper(int a, int b, char c){
    if(c == '+')
        return a + b;
    if(c == '-')
        return a - b;
    if(c == '*')
        return a * b;
    return a / b;
}

int main(){
    in>>s;
    for(int i = 0; i < s.size(); i++){
        if(isdigit(s[i])){
            nr = 0;
            while(isdigit(s[i])){
                nr = nr * 10 + (int)(s[i] - '0');
                i++;
            }
            n.push(nr);
            i --;
        }
        else{
            if(s[i] == '('){
                st.push(s[i]);
            }
            else
                if(s[i] == ')'){
                    while(st.top() != '('){
                        int k = n.top();
                        n.pop();
                        int x = oper(n.top(), k, st.top());
                        n.pop();
                        n.push(x);
                        st.pop();

                    }
                    st.pop();
                }
            else{
                if(!st.empty()){
                    if(priority(s[i]) == 1 && priority(st.top()) == 2)
                        st.push(s[i]);

                    else{
                        if(st.top() != '('){
                            int k = n.top();
                            n.pop();
                            int x = oper(n.top(), k, st.top());
                            n.pop();
                            n.push(x);
                            st.pop();
                            st.push(s[i]);
                        }
                        else
                            st.push(s[i]);
                    }
                }
                else{
                    st.push(s[i]);
                }
            }
        }
    }
    while(!st.empty()){
        if(st.top() != '(' && st.top() != ')'){
            int k = n.top();
            n.pop();
            int x = oper(n.top(), k, st.top());
            n.pop();
            n.push(x);
        }
        st.pop();
    }
    out<<n.top();
}