-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPREFIX EVAL.cpp
More file actions
58 lines (57 loc) · 1.38 KB
/
Copy pathPREFIX EVAL.cpp
File metadata and controls
58 lines (57 loc) · 1.38 KB
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
56
57
58
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
bool isoperand(char c)
{
// to check if the character of the string is a digit(operand)
return isdigit(c);
}
double evaluatePrefix(string s)
{
stack<double> st;
for(int i = s.length()-1 ; i>=0 ; i--)
{
if(isoperand(s[i]))
{
st.push(s[i]-'0');//Push operand to Stack
// To convert s[i] to digit subtract
// '0' from s[i].
}
else
{// Operator encountered
// Pop two elements from Stack
double opnd1 = st.top();
st.pop();
double opnd2 = st.top();
st.pop();
double res;
switch(s[i])
{
case '+':
res = opnd1+opnd2;
break;
case '-':
res = opnd1-opnd2;
break;
case '*':
res = opnd1*opnd2;
break;
case '/':
res = opnd1/opnd2;
break;
case '^':
res = pow(opnd1,opnd2);
break;
}
st.push(res);
}
}
return st.top();
}
int main()
{
string s = "-+7*45+20";
cout << evaluatePrefix(s) << endl;
return 0;
}