Pagini recente » Cod sursa (job #819356) | Cod sursa (job #2392934) | Cod sursa (job #2053024) | Cod sursa (job #491213) | Cod sursa (job #2676119)
#include <bits/stdc++.h>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
string s;
stack < char > st;
stack < int > n;
int nr;
int priority(char ch){
if(ch == '+' || ch == '-')
return 2;
return 1;
}
int oper(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 main(){
in>>s;
for(int i = 0; i < s.size(); i++){
if(isdigit(s[i])){
nr = 0;
while(isdigit(s[i])){
nr = nr * 10 + (int)(s[i] - '0');
i++;
}
n.push(nr);
i --;
}
else{
if(s[i] == '('){
st.push(s[i]);
}
else
if(s[i] == ')'){
while(st.top() != '('){
int k = n.top();
n.pop();
int x = oper(n.top(), k, st.top());
n.pop();
n.push(x);
st.pop();
}
st.pop();
}
else{
if(!st.empty()){
if(priority(s[i]) == 1 && priority(st.top()) == 2)
st.push(s[i]);
else{
if(st.top() != '('){
int k = n.top();
n.pop();
int x = oper(n.top(), k, st.top());
n.pop();
n.push(x);
st.pop();
st.push(s[i]);
}
else
st.push(s[i]);
}
}
else{
st.push(s[i]);
}
}
}
}
while(!st.empty()){
if(st.top() != '(' && st.top() != ')'){
int k = n.top();
n.pop();
int x = oper(n.top(), k, st.top());
n.pop();
n.push(x);
}
st.pop();
}
out<<n.top();
}