-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathBasic Calculator III.java
More file actions
41 lines (40 loc) · 1.24 KB
/
Basic Calculator III.java
File metadata and controls
41 lines (40 loc) · 1.24 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
class Solution {
public int calculate(String s) {
return helper(s, new int[]{0});
}
private int helper(String s, int[] idx) {
Stack<Integer> stack = new Stack<>();
int curr = 0;
char operator = '+';
while (idx[0] < s.length()) {
char c = s.charAt(idx[0]++);
if (Character.isDigit(c)) {
curr = curr * 10 + Character.getNumericValue(c);
}
if (c == '(') {
curr = helper(s, idx);
}
if ((!Character.isDigit(c) && c != ' ') || idx[0] == s.length()) {
if (operator == '+') {
stack.push(curr);
} else if (operator == '-') {
stack.push(-1 * curr);
} else if (operator == '*') {
stack.push(stack.pop() * curr);
} else if (operator == '/') {
stack.push(stack.pop() / curr);
}
if (c == ')') {
break;
}
operator = c;
curr = 0;
}
}
int result = 0;
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
}