Pagini recente » Cod sursa (job #3148157) | Cod sursa (job #1535205) | Cod sursa (job #3272207) | Cod sursa (job #1099646) | Cod sursa (job #1027589)
#include <fstream>
#include <stack>
#include <string>
#include <sstream>
int priority(char c) {
if(c == '(' || c == ')')
return 0;
if(c == '+' || c == '-')
return 1;
return 2;
}
bool isDigit(char c) {
return (c <= '9' && c >= '0');
}
int operate(int a, int b, char c) {
if(c == '+')
return a + b;
if(c == '-')
return a - b;
if(c == '*')
return a * b;
return a / b;
}
int RPN(std::string sz) {
std::stack<char> myS;
std::stack<int> myN;
for(int i = 0; i < sz.length(); ) {
if(isDigit(sz[i])) {
std::stringstream ss;
while(isDigit(sz[i])) {
ss << sz[i];
i++;
}
int aux;
ss >> aux;
myN.push(aux);
} else {
if(sz[i] == '(') {
myS.push('(');
} else if(sz[i] == ')') {
while(!myS.empty() && myS.top() != '(') {
int a, b;
char c = myS.top();
myS.pop();
b = myN.top();
myN.pop();
a = myN.top();
myN.pop();
myN.push(operate(a, b, c));
}
myS.pop();
} else {
while(!myS.empty() && priority(myS.top()) >= priority(sz[i])) {
int a, b;
char c = myS.top();
myS.pop();
b = myN.top();
myN.pop();
a = myN.top();
myN.pop();
myN.push(operate(a, b, c));
}
myS.push(sz[i]);
}
i++;
}
}
while(!myS.empty()) {
int a, b;
char c = myS.top();
myS.pop();
b = myN.top();
myN.pop();
a = myN.top();
myN.pop();
myN.push(operate(a, b, c));
}
return myN.top();
}
int main() {
std::ifstream in("evaluare.in");
std::ofstream out("evaluare.out");
std::string sz;
in >> sz;
out << RPN(sz);
return 0;
}