-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostfixEvaluation.cpp
50 lines (41 loc) · 1.05 KB
/
PostfixEvaluation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define _z ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int evaluatePostfix(string exp){
stack<int> st;
for(int i=0; i<exp.size(); i++){
if(isdigit(exp[i])){
st.push(exp[i]-'0');
}
else{
int val1 = st.top();
st.pop();
int val2 = st.top();
st.pop();
switch(exp[i]){
case '+':
st.push(val1+val2);
break;
case '-':
st.push(val2-val1);
break;
case '*':
st.push(val1*val2);
break;
case '/':
st.push(val2/val1);
break;
}
}
}
return st.top();
}
int main(){
string exp;
cout<<"Enter a postfix expression: "<<endl;
cin>>exp;
cout<<"Postfix evaluation is: "<<endl;
cout<<evaluatePostfix(exp);
return 0;
}