-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path227. Basic Calculator II.java
More file actions
39 lines (36 loc) · 1.05 KB
/
Copy path227. Basic Calculator II.java
File metadata and controls
39 lines (36 loc) · 1.05 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
public class Solution {
public int calculate(String s) {
// Stack to deal with * and /
Stack <Integer> st = new Stack<>();
int res = 0;
char sign = '+';
int len = s.length();
if (len == 0) {
return res;
}
int num = 0;
for (int i = 0; i < len; i++) {
char tmp = s.charAt(i);
if (tmp >= '0' && tmp <= '9') {
num = num * 10 + tmp - '0';
}
if ((!Character.isDigit(tmp) && tmp != ' ') || i == len - 1) {
if (sign == '+') {
st.push(num);
} else if (sign == '-') {
st.push(-num);
} else if (sign == '*') {
st.push(st.pop() * num);
} else if (sign == '/'){
st.push(st.pop() / num);
}
sign = tmp;
num = 0;
}
}
for (int i : st) {
res += i;
}
return res;
}
}