-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator.cc
44 lines (40 loc) · 1.38 KB
/
basic-calculator.cc
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
#include "leetcode.h"
using namespace std;
class Solution {
public:
int calculate(const string &str) {
size_t idx = 0;
return calculate(str, idx);
}
int calculate(const string &str, size_t &idx) const {
int64_t res = 0;
for (char opr = '+'; idx < str.size();) {
switch (str[idx]) {
case '+':
case '-': opr = str[idx++]; break;
case '(':
++idx;
res += opr == '+' ? calculate(str, idx) : -calculate(str, idx);
break;
case ')': ++idx; return res;
default:
if (isdigit(str[idx])) {
int64_t x = str[idx++] - '0';
while (idx < str.size() && isdigit(str[idx])) { x = x * 10 + str[idx++] - '0'; }
res += opr == '+' ? x : -x;
} else {
++idx;
}
break;
}
}
return res;
}
};
int main(int argc, char const *argv[]) {
Solution solution;
cout << solution.calculate("1-(2-(3-2))") << endl; // 0
cout << solution.calculate("1 + 1") << endl; // 2
cout << solution.calculate(" 2-1 + 2 ") << endl; // 3
cout << solution.calculate("(1+(4+5+2)-3)+(6+8)") << endl; // 23
}