-
Notifications
You must be signed in to change notification settings - Fork 28
/
Basic_Calculator.cpp
75 lines (74 loc) · 2.07 KB
/
Basic_Calculator.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
class Solution {
int toInt(string s) {
int n = 0;
istringstream sin(s);
sin >> n;
return n;
}
public:
int calculate(string s) {
if(s.empty()) return 0;
stack<int> stk;
int i = 0;
int n = (int)s.length();
while(i < n) {
while(i < n and s[i] == ' ') {
i++;
}
if(s[i] == ')') {
int sum = 0;
while(!stk.empty()) {
int top = stk.top();
stk.pop();
if(top == numeric_limits<int>::max()) {
stk.push(sum);
break;
}
if(top == numeric_limits<int>::min()) {
sum *= -1;
stk.push(sum);
break;
}
sum += top;
}
++i;
}
else {
int sign = 1;
if(s[i] == '-') {
sign = -1;
++i;
} else if(s[i] == '+') {
sign = 1;
++i;
}
while(i < n and s[i] == ' ') {
i++;
}
if(s[i] == '(') {
if(sign == 1) {
stk.push(numeric_limits<int>::max());
} else {
stk.push(numeric_limits<int>::min());
}
++i;
}
else {
int start = i;
while(i < n and s[i] >= '0' and s[i] <= '9') {
++i;
}
int num = toInt(s.substr(start, i - start));
num *= sign;
stk.push(num);
}
}
}
int result = 0;
while(!stk.empty()) {
result += stk.top();
stk.pop();
}
return result;
}
};