Pagini recente » Monitorul de evaluare | Cod sursa (job #2287328) | Cod sursa (job #3253890) | Cod sursa (job #3153612) | Cod sursa (job #2983733)
#include<bits/stdc++.h>
using namespace std;
const int N = 100009;
char expr[N];
ifstream in ("evaluare.in");
ofstream out("evaluare.out");
// auto& in = cin;
// auto& out = cout;
int comp(int x, int y, char c){
if(c == '+') return x + y;
if(c == '-') return x - y;
if(c == '*') return x * y;
if(c == '/') return x / y;
return 0; // to avoid compiler warning
}
int precedence(char c){
if(c == '*' || c == '/') return 2;
if(c == '+' || c == '-') return 1;
return 0;
}
void step(stack<int>& vals, stack<char>& ops){
// cout<<"for op: "<<ops.top()<<endl;
int s = vals.top(); vals.pop();
int f = vals.top(); vals.pop();
int o = ops.top(); ops.pop();
vals.push(comp(f, s, o));
// cout<<"computed: "<<vals.top()<<endl;
}
bool isDigit(char c){
return '0' <= c && c <= '9';
}
int main(){
stack<char> ops;
stack<int> vals;
in>>expr;
int n = strlen(expr);
int num = 0;
for(int i=0; i<n; i++)
{
if(isDigit(expr[i])){
num = 0;
while(i<n && isDigit(expr[i]))
{
num = num * 10 + expr[i] - '0';
i++;
}
vals.push(num);
// cout<<"found: "<<num<<endl;
i--; continue;
}
else if(expr[i] == '(')
ops.push(expr[i]);
else if(expr[i] == ')'){
while(!ops.empty() && ops.top() != '('){
step(vals, ops);
}
ops.pop();
}
else // operator
{
// cout<<"operator"<<endl;
while(!ops.empty() && precedence(ops.top()) >= precedence(expr[i]))
{
// cout<<"trying"<<endl;
step(vals, ops);
}
ops.push(expr[i]);
}
//out<<expr[i];
}
while(!ops.empty())
step(vals, ops);
// cout<<"found: "<<num<<endl;
out<<vals.top()<<endl;
return 0;
}