-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluRPN.java
More file actions
49 lines (43 loc) · 962 Bytes
/
EvaluRPN.java
File metadata and controls
49 lines (43 loc) · 962 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package leetcode;
import java.util.Stack;
/**
* Äæ²¨À¼±í´ïʽÇóÖµ
* @author HJH
*
*/
public class EvaluRPN {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strings = {"2", "1", "+", "3", "*"};
System.out.println(evalRPN(strings));
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i=0;i<tokens.length;i++){
try {
int num = Integer.parseInt(tokens[i]);
stack.push(num);
} catch (Exception e) {
// TODO: handle exception
int b = stack.pop();
int a = stack.pop();
stack.push(get(a, b, tokens[i]));
}
}
return stack.pop();
}
public static int get(int a,int b,String operation){
switch (operation) {
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
}