-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy patheval.cpp
117 lines (89 loc) · 2.59 KB
/
eval.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
// Eval Function for C++
#include <bits/stdc++.h>
using namespace std;
int precedence(char op){
if(op == '+'||op == '-')
return 1;
if(op == '*'||op == '/')
return 2;
return 0;
}
int applyOp(int a, int b, char op){
switch(op){
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
int eval(string expression){
int i;
// stack to store integer values.
stack <int> values;
// stack to store operators.
stack <char> ops;
for(i = 0; i < expression.length(); i++){
if(expression[i] == ' ')
continue;
else if(expression[i] == '('){
ops.push(expression[i]);
}
else if(isdigit(expression[i])){
int val = 0;
while(i < expression.length() &&
isdigit(expression[i]))
{
val = (val*10) + (expression[i]-'0');
i++;
}
values.push(val);
i--;
}
else if(expression[i] == ')')
{
while(!ops.empty() && ops.top() != '(')
{
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
if(!ops.empty())
ops.pop();
}
else
{
while(!ops.empty() && precedence(ops.top())
>= precedence(expression[i])){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
ops.push(expression[i]);
}
}
while(!ops.empty()){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
return values.top();
}
int main()
{
string expression = "10 + 20 * 30";
cout << eval(expression) << endl;
}
// Output
// 610