-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicCalculator.cpp
More file actions
36 lines (35 loc) · 936 Bytes
/
basicCalculator.cpp
File metadata and controls
36 lines (35 loc) · 936 Bytes
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
// Source: https://leetcode.com/problems/basic-calculator/
// Author: Miao Zhang
// Date: 2021-01-27
class Solution {
public:
int calculate(string s) {
long res = 0;
long num = 0;
int sign = 1;
stack<int> st;
for (auto &c: s) {
if (isdigit(c)) {
num = num * 10 + c -'0';
} else if (c == '+' || c == '-') {
res += sign * num;
num = 0;
sign = (c == '+') ? 1: -1;
} else if (c == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
} else if (c == ')') {
res += sign * num;
num = 0;
res *= st.top();
st.pop();
res += st.top();
st.pop();
}
}
res += sign * num;
return res;
}
};