-
Notifications
You must be signed in to change notification settings - Fork 1
/
BasicCalculator.java
50 lines (49 loc) · 1.39 KB
/
BasicCalculator.java
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
48
49
50
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 224. Basic Calculator
* 栈。基本原则:用栈来存储左括号前面的符号,因为括号内部的所有数组都应该根据括号前面的符号来选择取反或者不取反。
* @author LBW
*/
public class BasicCalculator {
public int calculate(String s) {
int num = 0;
Deque<Integer> stack = new ArrayDeque<>();
int sign = 1;
stack.push(sign);
int res = 0;
int idx = 0;
while (idx < s.length()) {
char c = s.charAt(idx);
if (c == ' ') {
idx += 1;
continue;
}
if (c == '+') {
sign = stack.peek();
idx += 1;
}
else if (c == '-') {
sign = -stack.peek();
idx += 1;
}
else if (c == '(') {
stack.push(sign);
idx += 1;
}
else if (c == ')') {
stack.pop();
idx += 1;
}
else {
num = 0;
while (idx < s.length() && s.charAt(idx) >= '0' && s.charAt(idx) <= '9') {
num = num * 10 + s.charAt(idx) - '0';
idx += 1;
}
res += sign * num;
}
}
return res;
}
}