-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvalPRN.java
More file actions
45 lines (39 loc) · 1.08 KB
/
Copy pathEvalPRN.java
File metadata and controls
45 lines (39 loc) · 1.08 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
package Stacks;
import org.junit.Test;
import java.util.Stack;
/**
* @author dekai.kong
* @difficult easy
* @create 2020-07-28 11:34
* @from 计算逆波兰表达式
**/
public class EvalPRN {
public EvalPRN() {
}
public int evalPrn(String[] s){
int ans = 0;
String op = "+-*/";
Stack<Integer> stack = new Stack<>();
for(int i = 0;i<s.length;i++){
if(op.indexOf(s[i])==-1){
stack.push(Integer.parseInt(s[i]));
}else{
int count = 0;
while(!stack.isEmpty() && ++count<2){
int b = stack.pop();
int a = stack.pop();
if(s[i] == "+") stack.push(a+b);
else if(s[i] == "-") stack.push(a-b);
else if(s[i] == "*") stack.push(a*b);
else if(s[i] == "/") stack.push(a/b);
}
}
}
ans = stack.pop();
return ans;
}
@Test
public void test() {
evalPrn(new String[]{"2","3","1","-","4","*","+"});
}
}