-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
38 lines (36 loc) · 1.04 KB
/
Solution.java
File metadata and controls
38 lines (36 loc) · 1.04 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
class Solution {
public int calculate(String s) {
Stack<Integer> st = new Stack<>();
int num = 0;
char sign = '+';
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') {
num = num * 10 + ch - '0';
}
if ((ch < '0' || ch > '9') && ch != ' ' || i == s.length() - 1) {
switch (sign) {
case '+':
st.push(num);
break;
case '-':
st.push(-num);
break;
case '/':
st.push(st.pop() / num);
break;
case '*':
st.push(st.pop() * num);
break;
}
sign = ch;
num = 0;
}
}
int res = 0;
while (!st.isEmpty()) {
res += st.pop();
}
return res;
}
}