Pagini recente » Cod sursa (job #669448) | Cod sursa (job #1215205) | Cod sursa (job #3219976) | Cod sursa (job #1246772) | Cod sursa (job #2837950)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
using ll = long long;
const string fn = "evaluare";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");
string s;
stack<int> t;
stack<char> op;
bool delim(char c){
return c == ' ';
}
bool opr(char c){
return c == '+' || c == '-' || c == '*' || c == '/';
}
int priority(char op){
if(op == '+' || op == '-')
return 1;
if(op == '*' || op == '/')
return 2;
return -1;
}
void calc(char op){
int r = t.top(); t.pop();
int l = t.top(); t.pop();
if(op == '+') t.push(l + r);
if(op == '-') t.push(l - r);
if(op == '*') t.push(l * r);
if(op == '/') t.push(l / r);
}
int main(){
fin >> s;
int i = 0;
for(int i = 0; i < (int)s.size(); ++i){
if(delim(s[i]))
continue;
if(s[i] == '(')
op.push('(');
else if(s[i] == ')'){
while(op.top() != '('){
calc(op.top());
op.pop();
}
op.pop();
}
else if(opr(s[i])){
char ac_op = s[i];
while(!op.empty() && priority(op.top()) >= priority(ac_op)){
calc(op.top());
op.pop();
}
op.push(ac_op);
}
else {
int nr = 0;
while(i < (int)s.size() && isdigit(s[i]))
nr = nr * 10 + s[i++] - '0';
--i;
t.push(nr);
}
}
while(!op.empty()){
calc(op.top());
op.pop();
}
fout << t.top() << '\n';
fin.close();
fout.close();
return 0;
}