Pagini recente » Cod sursa (job #3163827) | Cod sursa (job #2502739) | Cod sursa (job #679581) | Cod sursa (job #530441) | Cod sursa (job #1969862)
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
string S;
stack <int> Num;
stack <int> Op;
inline int Priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
void Operation() {
char op = Op.top();
Op.pop();
int y = Num.top();
Num.pop();
int x = Num.top();
Num.pop();
if (op == '+') Num.push(x + y);
if (op == '-') Num.push(x - y);
if (op == '*') Num.push(x * y);
if (op == '/') Num.push(x / y);
}
void Evaluate() {
Op.push('#');
for (unsigned int i = 0; i < S.size(); i++) {
if (S[i] == '(') {
Op.push(S[i]);
} else if (S[i] == ')') {
while (Op.top() != '(') Operation();
Op.pop();
} else {
int priority = Priority(S[i]);
if (priority > 0) {
while (Priority(Op.top()) >= priority) Operation();
Op.push(S[i]);
} else {
int val = 0;
while (S[i] >= '0' && S[i] <= '9') {
val = (val << 1) + (val << 3) + (S[i] - '0');
i++;
}
Num.push(val);
i--;
}
}
}
while (Op.top() != '#') Operation();
}
int main() {
ios_base :: sync_with_stdio(false);
getline(fin, S);
Evaluate();
fout << Num.top() << "\n";
return 0;
}