forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths5.cpp
More file actions
27 lines (27 loc) · 835 Bytes
/
Copy paths5.cpp
File metadata and controls
27 lines (27 loc) · 835 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
// OJ: https://leetcode.com/problems/basic-calculator-ii/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int calculate(string s) {
int num = 0, ans = 0, cur = 0;
char op = '+';
for (int i = 0, N = s.size(); i < N; ++i) {
if (isdigit(s[i])) num = 10 * num + (s[i] - '0');
if ((!isdigit(s[i]) && s[i] != ' ') || i == N - 1) {
if (op == '+') cur += num;
else if (op == '-') cur -= num;
else if (op == '*') cur *= num;
else cur /= num;
if (s[i] == '+' || s[i] == '-' || i == N - 1) {
ans += cur;
cur = 0;
}
op = s[i];
num = 0;
}
}
return ans;
}
};