-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculator2.java
More file actions
35 lines (33 loc) · 1.01 KB
/
BasicCalculator2.java
File metadata and controls
35 lines (33 loc) · 1.01 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
import java.util.Stack;
public class BasicCalculator2 {
public int calculate(String s) {
int num = 0;
Stack<Integer> stk = new Stack<>();
char operator = '+';
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char c = ch[i];
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) {
if (operator == '+') {
stk.push(num);
} else if (operator == '-') {
stk.push(-num);
} else if (operator == '*') {
stk.push(stk.pop() * num);
} else if (operator == '/') {
stk.push(stk.pop() / num);
}
operator = c;
num = 0;
}
}
int res = 0;
while (!stk.isEmpty()) {
res += stk.pop();
}
return res;
}
}