-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_227.java
More file actions
31 lines (29 loc) · 930 Bytes
/
Copy pathP_227.java
File metadata and controls
31 lines (29 loc) · 930 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
package leetcode.medium;
public class P_227 {
public int calculate(String s) {
final int n = s.length();
int res = 0;
int curr = 0;
int prev = 0;
char operation = '+';
for (int i = 0; i < n; i++) {
final char c = s.charAt(i);
if (Character.isDigit(c)) {
curr = (curr * 10) + (c - '0');
}
if (!Character.isDigit(c) && !Character.isWhitespace(c) || i == n - 1) {
if (operation == '+' || operation == '-') {
res += prev;
prev = (operation == '+') ? curr : -curr;
} else if (operation == '*') {
prev *= curr;
} else if (operation == '/') {
prev /= curr;
}
operation = c;
curr = 0;
}
}
return res + prev;
}
}