-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExpEval.cpp
More file actions
44 lines (42 loc) · 907 Bytes
/
Copy pathExpEval.cpp
File metadata and controls
44 lines (42 loc) · 907 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int cal(char operation, int x, int y)
{
if(operation == '+')
return x +y;
else if(operation == '-')
return x - y;
else if(operation == '*')
return x * y;
else if(operation == '/')
return x / y;
else
cout<<"Unexpected Error \n";
return -1;
}
int expEval(string exp){
char s;
int ans;
stack<int> S;
for(int i=0; i<exp.length(); i++){
s = exp.at(i);
if(s>='0' && s<='9'){
S.push(s- '0');
}else if(s == '+' || s == '-' || s == '*' || s == '/'){
int x = S.top();
S.pop();
int y = S.top();
S.pop();
ans = cal(s, x, y);
S.push(ans);
}
}
return ans;
}
int main(){
string exp;
cin >> exp;
int ans = expEval(exp);
cout << "Answer is " << ans;
return 0;
}