Pagini recente » Cod sursa (job #1497561) | Cod sursa (job #148358) | Cod sursa (job #970260) | Cod sursa (job #327218) | Cod sursa (job #2862561)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
using ll = long long;
const string myf = "evaluare";
ifstream fin(myf + ".in");
ofstream fout(myf + ".out");
string s;
stack<int> st;
stack<char> op;
inline bool isOp(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
inline int prior(char c) {
if (c == '+' || c == '-')
return 1;
if (c == '*' || c == '/')
return 2;
return -1;
}
void proc(char c) {
int R = st.top(); st.pop();
int L = st.top(); st.pop();
if (c == '+')
st.push(L + R);
if (c == '-')
st.push(L - R);
if (c == '*')
st.push(L * R);
if (c == '/')
st.push(L / R);
}
int main() {
fin >> s;
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] == ' ')
continue;
else if (s[i] == '(') {
op.push('(');
}
else if (s[i] == ')') {
while (op.top() != '(') {
proc(op.top());
op.pop();
}
op.pop();
}
else if (isOp(s[i])) {
while (!op.empty() && prior(op.top()) >= prior(s[i])) {
proc(op.top());
op.pop();
}
op.push(s[i]);
}
else {
int ac = 0;
while (i < (int)s.size() && isdigit(s[i]))
ac = ac * 10 + s[i++] - '0';
--i;
st.push(ac);
}
}
while (!op.empty()) {
proc(op.top());
op.pop();
}
fout << st.top() << '\n';
fin.close();
fout.close();
return 0;
}