-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator(AC).cpp
128 lines (113 loc) · 1.83 KB
/
basic-calculator(AC).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
121
122
123
124
125
126
127
128
// 1AC, in a real interview, this could be difficult.
#include <cctype>
#include <vector>
using namespace std;
typedef long long int LL;
class Solution {
public:
Solution() {
// Defining a precedence level is smarter than hard coding.
// Here I presume the operators are all one-character long.
int p = -1;
// Think about why.
pre['('] = p;
++p;
pre['&'] = p;
pre['|'] = p;
pre['^'] = p;
++p;
pre['+'] = p;
pre['-'] = p;
++p;
pre['*'] = p;
pre['/'] = p;
pre['%'] = p;
++p;
}
int calculate(string s) {
s = noSpace(s);
int i, j;
int n = s.length();
int val;
i = 0;
while (i < n) {
if (isdigit(s[i])) {
val = 0;
j = i;
while (j < n && isdigit(s[j])) {
val = val * 10 + (s[j++] - '0');
}
num.push_back(val);
i = j;
continue;
}
switch (s[i]) {
case '+':
case '-':
case '*':
case '/':
while (!op.empty() && pre[op.back()] >= pre[s[i]]) {
calc();
}
op.push_back(s[i]);
break;
case '(':
op.push_back(s[i]);
break;
case ')':
while (op.back() != '(') {
calc();
}
op.pop_back();
break;
}
++i;
}
while (num.size() > 1) {
calc();
}
val = num.back();
num.clear();
op.clear();
return val;
}
private:
int pre[256];
vector<LL> num;
vector<char> op;
string noSpace(string &s) {
string ss = "";
int n = s.length();
int i;
for (i = 0; i < n; ++i) {
if (s[i] == ' ') {
continue;
}
ss.push_back(s[i]);
}
return ss;
}
void calc() {
LL v1, v2, v3;
v2 = num.back();
num.pop_back();
v1 = num.back();
num.pop_back();
switch (op.back()) {
case '+':
v3 = v1 + v2;
break;
case '-':
v3 = v1 - v2;
break;
case '*':
v3 = v1 * v2;
break;
case '/':
v3 = v1 / v2;
break;
}
op.pop_back();
num.push_back(v3);
}
};