-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227. Basic Calculator II.cpp
44 lines (43 loc) · 1.34 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
class Solution {
public:
int calculate(string s) {
long res = 0;
bool isAdd = true;
long cache = 0;
long curr = 0;
enum operation {multiply, divide, neither};
operation lastOperation = neither;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ') continue;
if (isdigit(s[i])) {
curr = 10 * curr + (s[i] - '0');
if (i + 1 < s.length() && isdigit(s[i+1])) continue;
if (lastOperation == neither) cache = curr;
else if (lastOperation == multiply) cache *= curr;
else cache /= curr;
curr = 0;
}
else if (s[i] == '+') {
if (isAdd) res += cache;
else res -= cache;
isAdd = true;
lastOperation = neither;
}
else if (s[i] == '-') {
if (isAdd) res += cache;
else res -= cache;
isAdd = false;
lastOperation = neither;
}
else if (s[i] == '*') {
lastOperation = multiply;
}
else if (s[i] == '/') {
lastOperation = divide;
}
}
if (isAdd) res += cache;
else res -= cache;
return res;
}
};