-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBasicCalculator2.java
More file actions
27 lines (27 loc) · 906 Bytes
/
BasicCalculator2.java
File metadata and controls
27 lines (27 loc) · 906 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
public class Solution {
public int calculate(String s) {
Deque<Integer> stack = new ArrayDeque<>();
char sign = '+';
int n = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ("+-*/".indexOf(ch) >= 0) {
sign = ch;
} else if (ch != ' ') {
n = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
n = n * 10 + (s.charAt(i) - '0');
i++;
}
i--;
if (sign == '+') stack.push(n);
else if (sign == '-') stack.push(-n);
else if (sign == '*') stack.push(stack.pop() * n);
else if (sign == '/') stack.push(stack.pop() / n);
}
}
int res = 0;
for (int i : stack) res += i;
return res;
}
}