-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicCalculatorII.cpp
More file actions
39 lines (37 loc) · 1.09 KB
/
basicCalculatorII.cpp
File metadata and controls
39 lines (37 loc) · 1.09 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
// Source: https://leetcode.com/problems/basic-calculator-ii/
// Author: Miao Zhang
// Date: 2021-01-28
class Solution {
public:
int calculate(string s) {
stack<int> st;
long num = 0;
char pre_op = '+';
for(int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
num = 10 * num + s[i] - '0';
}
if (i == s.size() - 1 || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
if (pre_op == '+') st.push(num);
else if (pre_op == '-') st.push(-num);
else if (pre_op == '*') {
int num2 = st.top();
st.pop();
st.push(num2 * num);
} else if (pre_op == '/') {
int num2 = st.top();
st.pop();
st.push(num2 / num);
}
pre_op = s[i];
num = 0;
}
}
int res = 0;
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};