Pagini recente » Cod sursa (job #2410311) | Cod sursa (job #2196408) | Cod sursa (job #2905568) | Cod sursa (job #1281770) | Cod sursa (job #1870957)
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
const int maxn = 1e5 + 5;
stack <int> Nr;
stack <char> Op;
string S;
inline int Priority (char op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
return 0;
}
inline void Operation() {
char op = Op.top(); Op.pop();
int y = Nr.top(); Nr.pop();
int x = Nr.top(); Nr.pop();
if (op == '+') {
Nr.push(x + y);
} else if (op == '-') {
Nr.push(x - y);
} else if (op == '*') {
Nr.push(x * y);
} else if (op == '/') {
Nr.push(x / y);
}
}
void Solve() {
int i, priority, val;
Op.push('#');
for (i = 0; i < S.size(); i++) {
if (S[i] == '(') {
Op.push(S[i]);
} else if (S[i] == ')') {
while (Op.top() != '(') {
Operation();
}
Op.pop();
} else {
priority = Priority(S[i]);
if (priority > 0) {
while (Priority(Op.top()) >= priority) {
Operation();
}
Op.push(S[i]);
} else {
val = 0;
while (S[i] >= '0' && S[i] <= '9') {
val = (val << 1) + (val << 3) + (S[i] - '0');
i++;
}
Nr.push(val);
i--;
}
}
}
while (Op.top() != '#') {
Operation();
}
}
int main() {
ios_base :: sync_with_stdio (false);
getline(fin, S);
Solve();
fout << Nr.top();
fin.close();
fout.close();
return 0;
}