-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path224.cpp
More file actions
41 lines (41 loc) · 1.06 KB
/
224.cpp
File metadata and controls
41 lines (41 loc) · 1.06 KB
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
class Solution {
public:
int calculate(string s) {
int res = 0;
int sign = 1;
stack<int> st;
int index = 0;
while (index < s.size()) {
if (isdigit(s[index])) {
int num = 0;
num += s[index] - '0';
while (index + 1 < s.size() && isdigit(s[index + 1])) {
index++;
num *= 10;
num += s[index] - '0';
}
res += sign * num;
}
else if (s[index] == '+') {
sign = 1;
}
else if (s[index] == '-') {
sign = -1;
}
else if (s[index] == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
}
else if (s[index] == ')') {
res *= st.top();
st.pop();
res += st.top();
st.pop();
}
index++;
}
return res;
}
};