-
Notifications
You must be signed in to change notification settings - Fork 1
/
227 Basic Calculator II .cpp
64 lines (64 loc) · 1.81 KB
/
227 Basic Calculator II .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
class Solution {
public:
int calculate(string s) {
auto it = s.begin();
auto hasNext = [&] () {
while (it != end(s) && *it == ' ') {
it++;
}
return it != end(s);
};
auto read = [&] () {
while (it != end(s) && *it == ' ') {
it++;
}
string s = "";
if (isdigit(*it)) {
while (it != end(s) && isdigit(*it)) {
s += *it;
it++;
}
} else {
s += *it;
it++;
}
return s;
};
vector<string> tokens;
while (hasNext()) {
tokens.push_back(read());
}
auto prec = [] (const string &op) {
if (op == "*" || op == "/") {
return 1;
}
return 0;
};
auto calc = [] (const int &x, const string &op, const int &y) {
if (op == "+") {
return x + y;
} else if (op == "-") {
return x - y;
} else if (op == "*") {
return x * y;
} else if (op == "/") {
return x / y;
}
return -212121;
};
function<int(vector<string>::iterator &, int)> eval = [&] (vector<string>::iterator &it, int pre) {
auto lhs = stoi(*it);
it++;
while (it != end(tokens) && prec(*it) >= pre) {
auto &op = *it;
it++;
auto nowPre = prec(op) + 1;
auto rhs = eval(it, nowPre);
lhs = calc(lhs, op, rhs);
}
return lhs;
};
auto tokensIt = begin(tokens);
return eval(tokensIt, -1);
}
};