-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfab.cc
More file actions
56 lines (52 loc) · 1.28 KB
/
Copy pathfab.cc
File metadata and controls
56 lines (52 loc) · 1.28 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
#include <iostream>
#include <stack>
const int kReturnResult = 1;
const int KComputeAndReturn = 2;
const int kCall = 3;
int pop(std::stack<int>& heap) {
int num = heap.top();
heap.pop();
return num;
}
int fac(int n) {
std::stack<int> heap;
heap.push(kReturnResult);
heap.push(n);
heap.push(kCall);
while(!heap.empty()) {
int op = pop(heap);
switch (op) {
case kCall: {
n = pop(heap);
if (n < 2) {
op = pop(heap);
heap.push(1);
heap.push(op);
} else {
heap.push(n);
heap.push(KComputeAndReturn);
heap.push(n-1);
heap.push(kCall);
}
break;
}
case KComputeAndReturn: {
int tmp_fac = pop(heap);
n = pop(heap);
op = pop(heap);
tmp_fac = tmp_fac * n;
heap.push(tmp_fac);
heap.push(op);
break;
}
case kReturnResult: {
return pop(heap);
break;
}
}
}
return 0;
}
int main() {
std::cout << fac(5) << std::endl;
}