Pagini recente » Cod sursa (job #2532194) | Borderou de evaluare (job #2013118) | Cod sursa (job #3275273) | Cod sursa (job #558266) | Cod sursa (job #1461705)
#include <cstdio>
#include <stack>
#include <cctype>
#include <cstring>
using namespace std;
const int nmx = 100005;
char s[nmx];
stack <int> st;
stack <char> ST;
int prioritate(const char c) {
if(c == '(' || c == ')')
return 0;
if(c == '+' || c == '-')
return 1;
return 2;
}
int calc(int val1, int val2, char semn) {
if(semn == '+')
return val1 + val2;
if(semn == '-')
return val1 - val2;
if(semn == '*')
return val1 * val2;
return val1 / val2;
}
int evaluare() {
int val1, val2;
ST.push('(');
int lun = strlen(s) + 1;
s[lun-1] = ')';
for(int i = 0; i < lun; ++i) {
if(s[i] == '(') {
ST.push('(');
continue;
}
if(s[i] == ')') {
while(not ST.empty() && ST.top() != '(') {
/// val2 - val1
val2 = st.top();
st.pop();
val1 = st.top();
st.pop();
int aux =calc(val1,val2,ST.top());
st.push(calc(val1,val2,ST.top()));
ST.pop();
}
ST.pop();
continue;
}
if(isdigit(s[i])) {
val1 = 0;
while(isdigit(s[i])) {
val1 = val1 * 10 + (int)s[i] - 48;
++ i;
}
-- i;
st.push(val1);
continue;
}
while(prioritate(ST.top()) >= prioritate(s[i])) {
val2 = st.top();
st.pop();
val1 = st.top();
st.pop();
st.push(calc(val1,val2,ST.top()));
ST.pop();
}
ST.push(s[i]);
}
return st.top();
}
int main() {
freopen("evaluare.in" ,"r", stdin);
freopen("evaluare.out", "w", stdout);
scanf("%s", s);
printf("%d\n", evaluare());
return 0;
}