-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluation of Postfix Expression.cpp
55 lines (48 loc) · 1.11 KB
/
Evaluation of Postfix Expression.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
51
52
53
54
55
//{ Driver Code Starts
// C++ program to evaluate value of a postfix expression
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to evaluate a postfix expression.
int evaluatePostfix(string S)
{
// Your code here
stack<int> st;
for(auto c:S){
if(c == '*' || c == '/' || c == '+' || c == '-'){
int b = st.top();
st.pop();
int a = st.top();
st.pop();
int res;
if(c == '*') res = a*b;
else if(c == '/') res = a/b;
else if(c == '+') res = a+b;
else res = a-b;
st.push(res);
}
else st.push((int)c-'0');
}
return st.top();
}
};
//{ Driver Code Starts.
// Driver program to test above functions
int main()
{
int t;
cin>>t;
cin.ignore(INT_MAX, '\n');
while(t--)
{
string S;
cin>>S;
Solution obj;
cout<<obj.evaluatePostfix(S)<<endl;
}
return 0;
}
// } Driver Code Ends