forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s4.cpp
31 lines (31 loc) · 911 Bytes
/
s4.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
// OJ: https://leetcode.com/problems/basic-calculator-ii/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int calculate(string s) {
stack<int> st;
int ans = 0, num = 0;
char op = '+';
for (int i = 0, N = s.size(); i < N; ++i) {
if (isdigit(s[i])) {
while (i < N && isdigit(s[i])) num = 10 * num + (s[i++] - '0');
--i;
}
if ((!isdigit(s[i]) && s[i] != ' ') || i == N - 1) {
if (op == '+') st.push(num);
else if (op == '-') st.push(-num);
else if (op == '*') st.top() *= num;
else if (op == '/') st.top() /= num;
op = s[i];
num = 0;
}
}
while (st.size()) {
ans += st.top();
st.pop();
}
return ans;
}
};