Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
代码如下:
1 public class Solution { 2 public int evalRPN(String[] s) { 3 4 Stack<Integer> stack1=new Stack<>(); 5 for(int i=0;i<s.length;i++) 6 { 7 if(s[i].equals("+")) 8 { 9 int a=stack1.pop(); 10 int b=stack1.pop(); 11 stack1.push(a+b); 12 } 13 else if(s[i].equals("-")) 14 { 15 int a=stack1.pop(); 16 int b=stack1.pop(); 17 stack1.push(b-a); 18 } 19 else if(s[i].equals("*")) 20 { 21 int a=stack1.pop(); 22 int b=stack1.pop(); 23 stack1.push(a*b); 24 } 25 else if(s[i].equals("/")) 26 { 27 int a=stack1.pop(); 28 int b=stack1.pop(); 29 stack1.push(b/a); 30 } 31 else 32 { 33 try{stack1.push(Integer.parseInt(s[i].trim()));} 34 catch(NumberFormatException e){} 35 36 } 37 38 } 39 return stack1.peek(); 40 } 41 }
浙公网安备 33010602011771号