-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecursive.cpp
More file actions
77 lines (69 loc) · 1.35 KB
/
recursive.cpp
File metadata and controls
77 lines (69 loc) · 1.35 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
class evaluator
{
private:
string infix_;
mutable const char* p;
public:
void init(string infix) { infix_ = infix; }
int evaluate() const
{
p = infix_.c_str();
return evaluate_expression();
}
private:
int evaluate_factor() const // factor := number | '(' expression ')'
{
if (*p == '(') {
++p;
int v = evaluate_expression();
assert(*p == ')');
++p;
return v;
} else if (*p >= '0' && *p <= '9') {
return *p++ - '0';
} else {
assert(false);
}
}
int evaluate_term() const // term := factor { ('*'|'/') factor }
{
int a = evaluate_factor();
while (*p == '*' || *p == '/') {
char op = *p++;
int b = evaluate_factor();
switch (op) {
default: assert(false);
case '*': a *= b; break;
case '/': a /= b; break;
}
}
return a;
}
int evaluate_expression() const // expression := term { ('+'|'-') term }
{
int a = evaluate_term();
while (*p == '+' || *p == '-') {
char op = *p++;
int b = evaluate_term();
switch (op) {
default: assert(false);
case '+': a += b; break;
case '-': a -= b; break;
}
}
return a;
}
};
int main()
{
string expression = "1*(2+3/4)";
evaluator e;
e.init(expression);
cout << "infix : " << expression << endl;
cout << "evaluate: " << e.evaluate() << endl;
return 0;
}