Pagini recente » Cod sursa (job #1929524) | Cod sursa (job #2190396) | Cod sursa (job #571729) | Cod sursa (job #1996517) | Cod sursa (job #2308287)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <stack>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
bool isoperator(char x) {
if(x == '+' || x == '-' || x == '*' || x == '/')
return 1;
return 0;
}
int priority(char x) {
if(x == '+' || x == '-')
return 1;
return 2;
}
int compute(int a, char op, int b) {
if(op == '+')
return a + b;
if(op == '-')
return a - b;
if(op == '*')
return a * b;
if(op == '/')
return a / b;
}
int main() {
string s;
in >> s;
stack<char> op;
stack<int> values;
for(int i = 0; i < s.size(); i ++) {
char x = s[i];
if(x == '(')
op.push(x);
else if(x == ')') {
if(op.top() == '(')
op.pop();
else {
while(op.top() != '(') {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
values.push(compute(b, op.top(), a));
op.pop();
}
op.pop();
}
} else if(isoperator(x)) {
while(op.size() && isoperator(op.top()) && priority(x) <= priority(op.top())) {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
values.push(compute(b, op.top(), a));
op.pop();
}
op.push(x);
} else {
int nr = 0;
while(i < s.size() && isdigit(s[i])) {
nr *= 10;
nr += (s[i] - '0');
i ++;
}
if(i < s.size())
i --;
values.push(nr);
}
}
while(op.size()) {
int a = values.top();
values.pop();
int b = values.top();
values.pop();
values.push(compute(b, op.top(), a));
op.pop();
}
out << values.top();
return 0;
}