forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculator2.java
More file actions
57 lines (51 loc) · 1.72 KB
/
BasicCalculator2.java
File metadata and controls
57 lines (51 loc) · 1.72 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @author JackWu
* @version 1.0
*/
public class BasicCalculator2 {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.calculate("3/2 "));
}
static class Solution {
public int calculate(String s) {
int res = 0;
char preSign = '+';
int n = s.length();
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
int num = 0;
if (s.charAt(i) == ' '){
continue;
}else if (Character.isDigit(s.charAt(i))){
while (i < n && Character.isDigit(s.charAt(i))) {
num = num * 10 + Integer.parseInt(String.valueOf(s.charAt(i)));
i++;
}
i--;
switch (preSign) {
case '+':stack.push(num);break;
case '-':stack.push(-num);break;
case '*':{
stack.push(stack.pop() * num);
break;
}
case '/':{
stack.push(stack.pop() / num);
break;
}
}
}else if (s.charAt(i) == '+' || s.charAt(i) == '-'
|| s.charAt(i) == '*' || s.charAt(i) == '/') {
preSign = s.charAt(i);
}
}
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
}