forked from singlemancombat/interview-preparation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCaculatorII.java
More file actions
36 lines (36 loc) · 1.18 KB
/
Copy pathBasicCaculatorII.java
File metadata and controls
36 lines (36 loc) · 1.18 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
public class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) return 0;
int len = s.length();
char[] chs = s.toCharArray();
Deque<Integer> deque = new LinkedList<>();
int num = 0;
char operator = '+';
for (int i = 0; i < len; i++) {
if (chs[i] >= '0' && chs[i] <= '9') {
num = num * 10 + chs[i] - '0';
}
if ((!(chs[i] >= '0' && chs[i] <= '9') && chs[i] != ' ') || i == len - 1) { // 易错点
switch (operator) {
case '+' :
deque.push(num);
break;
case '-' :
deque.push(-num);
break;
case '*' :
deque.push(deque.pop() * num);
break;
case '/' :
deque.push(deque.pop() / num);
break;
}
operator = chs[i];
num = 0;
}
}
int res = num;
for (int number : deque) res += number;
return res;
}
}