Pagini recente » Cod sursa (job #1355522) | Cod sursa (job #768549) | Cod sursa (job #2853456) | Cod sursa (job #2124812) | Cod sursa (job #2672523)
#include <bits/stdc++.h>
using namespace std;
inline int applyOp(const int X, const int Y, const char OP) {
if(OP == '+') return X + Y;
if(OP == '-') return X - Y;
if(OP == '*') return X * Y;
return X / Y;
}
inline int opPrec(const char X) {
if(X == '+' || X == '-') return 1;
if(X == '*' || X == '/') return 2;
return 0;
}
int evalExp(const string X) {
stack<int> nbs;
stack<char> ops;
for(int i = 0; i < X.length(); ++i) {
if(X[i] == ' ') continue;
if(isdigit(X[i])) {
int nbc = 0;
while(i < X.length() && isdigit(X[i]))
nbc = nbc * 10 + X[i] - '0', ++i;
--i, nbs.push(nbc);
} else if(X[i] == '(') {
ops.push(X[i]);
} else if(X[i] == ')') {
while(!ops.empty() && ops.top() != '(') {
int nb1 = nbs.top(); nbs.pop();
int nb2 = nbs.top(); nbs.pop();
char op = ops.top(); ops.pop();
nbs.push(applyOp(nb2, nb1, op));
}
if(!ops.empty()) ops.pop();
} else {
while(!ops.empty() && opPrec(X[i]) <= opPrec(ops.top())) {
int nb1 = nbs.top(); nbs.pop();
int nb2 = nbs.top(); nbs.pop();
char op = ops.top(); ops.pop();
nbs.push(applyOp(nb2, nb1, op));
}
ops.push(X[i]);
}
}
while(!ops.empty()) {
int nb1 = nbs.top(); nbs.pop();
int nb2 = nbs.top(); nbs.pop();
char op = ops.top(); ops.pop();
nbs.push(applyOp(nb2, nb1, op));
}
return nbs.top();
}
int main()
{
string inp = "100*(2+12)/14*0+1-1-5+6";
cout<<evalExp(inp);
return 0;
}