Pagini recente » Cod sursa (job #3242719) | Cod sursa (job #2615520) | Cod sursa (job #1784122) | Cod sursa (job #1549195) | Cod sursa (job #3294461)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
bool delim(char c) {
return c == ' ';
}
bool is_op(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int priority(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return -1;
}
void process_op(stack<int>& st, char op) {
int r = st.top(); st.pop();
int l = st.top(); st.pop();
switch (op) {
case '+': st.push(l + r); break;
case '-': st.push(l - r); break;
case '*': st.push(l * r); break;
case '/': st.push(l / r); break;
}
}
int evaluate(string& s) {
stack<int> st;
stack<char> op;
for (int i = 0; i < s.size(); i++) {
if (delim(s[i]))
continue;
if (s[i] == '(')
op.push('(');
else if (s[i] == ')') {
while (op.top() != '(') {
process_op(st, op.top());
op.pop();
}
op.pop();
} else if (is_op(s[i])) {
char curr_op = s[i];
while (!op.empty() && priority(op.top()) >= priority(curr_op)) {
process_op(st, op.top());
op.pop();
}
op.push(curr_op);
} else {
int num = 0;
while (i < s.size() && s[i] >= '0' && s[i] <= '9')
num = num * 10 + (s[i++] - '0');
i--;
st.push(num);
}
}
while (!op.empty()) {
process_op(st, op.top());
op.pop();
}
return st.top();
}
int main() {
f >> s;
g << evaluate(s);
f.close();
g.close();
return 0;
}