-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic Calculator 2.java
71 lines (67 loc) · 1.83 KB
/
Basic Calculator 2.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Solution {
public int calculate(String s) {
return solvePostFix(postFix(s));
}
private int solvePostFix(List<Object> list) {
Stack<Integer> st = new Stack();
for (Object o : list) {
if (o instanceof Integer) {
st.push((Integer) o);
} else {
char ch = (Character) o;
int b = st.pop();
int a = st.pop();
if (ch == '+') {
st.push(a + b);
} else if (ch == '-') {
st.push(a - b);
} else if (ch == '*') {
st.push(a * b);
} else if (ch == '/') {
st.push(a / b);
}
}
}
return st.pop();
}
private List<Object> postFix(String s) {
List<Object> list = new ArrayList();
Stack<Character> st = new Stack();
int num = 0;
for (char ch : s.toCharArray()) {
if (ch == ' ')
continue;
if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
} else {
list.add(num);
num = 0;
while (!st.isEmpty() && prec(st.peek()) >= prec(ch)) {
list.add(st.pop());
}
st.push(ch);
}
}
list.add(num);
while (!st.isEmpty()) {
list.add(st.pop());
}
return list;
}
private int prec(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
}