-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculator.java
More file actions
80 lines (72 loc) · 2.46 KB
/
BasicCalculator.java
File metadata and controls
80 lines (72 loc) · 2.46 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package leetcode;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
/**
* BasicCalculator
* https://leetcode-cn.com/problems/basic-calculator/
* 224. 基本计算器
* https://leetcode-cn.com/problems/basic-calculator/solution/zhan-mo-ni-ji-suan-qi-by-oshdyr-21qv/
*
* @since 2021-03-10
*/
public class BasicCalculator {
public static void main(String[] args) {
BasicCalculator sol = new BasicCalculator();
System.out.println(sol.calculate("2 - 1+2"));
System.out.println(sol.calculate("10 - (10 - 2)"));
System.out.println(sol.calculate("(1+(4+5+2)-3)+(6+8)"));
}
public int calculate(String s) {
Set<Character> chars = new HashSet<>();
chars.add('(');
chars.add(')');
chars.add('+');
chars.add('-');
chars.add(' ');
Stack<Character> operators = new Stack<>();
Stack<Integer> values = new Stack<>();
int value = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (chars.contains(c)) {
if (c == '(') {
operators.add(c);
} else if (c == ')') {
while (operators.peek() != '(') {
int last = values.pop();
char lastOp = operators.pop();
if (lastOp == '+') {
value = last + value;
} else {
value = last - value;
}
}
operators.pop();
} else if (c == '+' || c == '-') {
// 减法不能直接从后往前计算, 需要对应更改值为负数
if (!operators.isEmpty() && operators.peek() == '-') {
value = -1 * value;
operators.pop();
operators.add('+');
}
values.add(value);
operators.add(c);
value = 0;
}
} else {
value = value * 10 + (int) (c - '0');
}
}
while (!operators.isEmpty()) {
int last = values.pop();
char lastOp = operators.pop();
if (lastOp == '+') {
value = last + value;
} else {
value = last - value;
}
}
return value;
}
}