-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path227.Basic-Calculator-II.java
66 lines (59 loc) · 1.88 KB
/
227.Basic-Calculator-II.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
// https://leetcode.com/problems/basic-calculator-ii/
//
// algorithms
// Medium (33.20%)
// Total Accepted: 105,781
// Total Submissions: 318,617
class Solution {
public int calculate(String s) {
s = s.trim();
LinkedList<String> stack = new LinkedList<>();
int len = s.length(), i = 0;
while (i < len) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') {
int j = i;
while (j < len && s.charAt(j) >= '0' && s.charAt(j) <= '9') {
j++;
}
stack.offer(s.substring(i, j));
i = j;
} else if (ch == '+' || ch == '-') {
stack.offer(s.substring(i, i + 1));
i++;
} else if (ch == '*' || ch == '/') {
i++;
while (s.charAt(i) == ' ') {
i++;
}
int j = i;
while (j < len && s.charAt(j) >= '0' && s.charAt(j) <= '9') {
j++;
}
int preNum = Integer.valueOf(stack.pollLast());
int nextNum = Integer.valueOf(s.substring(i, j));
if (ch == '*') {
stack.offer(String.valueOf(preNum * nextNum));
} else {
stack.offer(String.valueOf(preNum / nextNum));
}
i = j;
} else {
i++;
}
}
int res = Integer.valueOf(stack.pollFirst());
int op = 1;
while (stack.size() > 0) {
String str = stack.pollFirst();
if (str.equals("-")) {
op = -1;
} else if (str.equals("+")) {
op = 1;
} else {
res = res + (op * Integer.valueOf(str));
}
}
return res;
}
}