-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculatorII.java
More file actions
47 lines (43 loc) · 1.44 KB
/
BasicCalculatorII.java
File metadata and controls
47 lines (43 loc) · 1.44 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
39
40
41
42
43
44
45
46
47
class Solution {
private final char[] ops = new char[]{'+', '-', '*', '/'};
public int doOp(char op, int left, int right) {
switch (op) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left/right;
default:
return 0;
}
}
public int dfs(String s, int startIndexInclusive, int endIndexExclusive) {
for (int i = endIndexExclusive - 1; i >= startIndexInclusive; i--) {
char op = s.charAt(i);
if (op == '+' || op == '-') {
return doOp(op, dfs(s, startIndexInclusive, i), dfs(s, i + 1, endIndexExclusive));
}
}
for (int i = endIndexExclusive - 1; i >= startIndexInclusive; i--) {
char op = s.charAt(i);
if (op == '*' || op == '/') {
return doOp(op, dfs(s, startIndexInclusive, i), dfs(s, i + 1, endIndexExclusive));
}
}
int value = 0;
for (int i = startIndexInclusive; i < endIndexExclusive; i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
continue;
}
value = value * 10 + c - '0';
}
return value;
}
public int calculate(String s) {
return dfs(s, 0, s.length());
}
}