-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode150.java
43 lines (38 loc) · 996 Bytes
/
leetcode150.java
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
public class Solution {
public int evalRPN(String[] tokens) {
int length = tokens.length;
if(tokens == null || tokens.length == 0)
return 0;
if(length == 1)
return Integer.valueOf(tokens[0]);
int params_1;
int params_2; //两个参数用来保存运算参数
Stack<Integer> nums = new Stack<Integer>(); //用来保存数字
for(int i=0;i<length;i++){
if(tokens[i].equals("+")){
params_2 = nums.pop();
params_1 = nums.pop();
nums.push(params_1+params_2);
}
else if(tokens[i].equals("-")){
params_2 = nums.pop();
params_1 = nums.pop();
nums.push(params_1-params_2);
}
else if(tokens[i].equals("*")){
params_2 = nums.pop();
params_1 = nums.pop();
nums.push(params_1*params_2);
}
else if(tokens[i].equals("/")){
params_2 = nums.pop();
params_1 = nums.pop();
nums.push(params_1/params_2);
}
else{
nums.push(Integer.valueOf(tokens[i]));
}
}
return nums.pop();
}
}