-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBasicCalculatorII.java
More file actions
35 lines (35 loc) · 1008 Bytes
/
BasicCalculatorII.java
File metadata and controls
35 lines (35 loc) · 1008 Bytes
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
public class Solution {
public int calculate(String s) {
int len = s.length();
if (len == 0) {
return 0;
}
Stack<Integer> st = new Stack<>();
char sign = '+';
int num = 0;
for (int i = 0; i < len; ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (int) (c - '0');
}
if (!Character.isDigit(c) && c != ' ' || 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 = c;
num = 0;
}
}
int res = 0;
for (int val: st) {
res += val;
}
return res;
}
}