-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathPrefixEvaluation.cpp
121 lines (80 loc) · 1.75 KB
/
PrefixEvaluation.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<iostream>
#include<stack>
#include<math.h>
/*Program to do Prefix expression evaluation using stack
It is similar to the Postfix evaluation using stack, in this case we just have to read the expression from right to left;
*/
using namespace std;
//function protorypes-
int getResultPre(string exp);
bool isOperand(char c);
bool isOperator(char c);
int PerformOps(double a,double b ,char c);
int getResultPre(string exp)
{
stack<double>S;
//scanning the expression from right to left
for(int i = exp.length() ; i >= 0 ; i--)
{
if(exp[i] == ',' || exp[i] == ' ') continue;
//if the scanned input is an operator, then pop 2 operands from stack and operate them
else if(isOperator(exp[i]) && !S.empty())
{
double a = S.top(); S.pop();
double b = S.top() ; S.pop();
double result = PerformOps(a,b,exp[i]);
//pusing the result in stack
S.push(result);
}
//push it to the stack
else if(isOperand(exp[i]))
{
int op = 0;
if(isdigit(exp[i]))
{
//converting the string to integer
op = (exp[i]-'0');
S.push(op);
}
}
}
return abs(S.top()); //result is stored at top;
}
bool isOperand(char c)
{
if(c >= 'a' && c <= 'z' ) return true;
if(c >='A' && c<= 'Z') return true;
if(c>='0' && c<='9') return true;
return false;
}
bool isOperator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/') return true;
return false;
}
int PerformOps(double a , double b, char opt)
{
switch(opt)
{
case '+':
return a+b;
break;
case '-':
return a-b;
break;
case '*' :
return a*b;
break;
case '/' :
return a/b;
break;
default:
cout<<"Incorrect operand";
break;
}
}
int main()
{
cout<<getResultPre("/*+9233");
return 0;
}