|
| 1 | +/* |
| 2 | +Evaluate the value of an arithmetic expression in Reverse Polish Notation. |
| 3 | + |
| 4 | +Valid operators are +, -, *, /. Each operand may be an integer or another expression. |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +Input Format |
| 9 | + |
| 10 | +The only argument given is character array A. |
| 11 | +Output Format |
| 12 | + |
| 13 | +Return the value of arithmetic expression formed using reverse Polish Notation. |
| 14 | +For Example |
| 15 | + |
| 16 | +Input 1: |
| 17 | + A = ["2", "1", "+", "3", "*"] |
| 18 | +Output 1: |
| 19 | + 9 |
| 20 | +Explaination 1: |
| 21 | + starting from backside: |
| 22 | + *: ( )*( ) |
| 23 | + 3: ()*(3) |
| 24 | + +: ( () + () )*(3) |
| 25 | + 1: ( () + (1) )*(3) |
| 26 | + 2: ( (2) + (1) )*(3) |
| 27 | + ((2)+(1))*(3) = 9 |
| 28 | + |
| 29 | +Input 2: |
| 30 | + A = ["4", "13", "5", "/", "+"] |
| 31 | +Output 2: |
| 32 | + 6 |
| 33 | +Explaination 2: |
| 34 | + +: ()+() |
| 35 | + /: ()+(() / ()) |
| 36 | + 5: ()+(() / (5)) |
| 37 | + 1: ()+((13) / (5)) |
| 38 | + 4: (4)+((13) / (5)) |
| 39 | + (4)+((13) / (5)) = 6 |
| 40 | + |
| 41 | + */ |
| 42 | + |
| 43 | + public class Solution { |
| 44 | + public int evalRPN(ArrayList<String> A) { |
| 45 | + if(A.size()== 0) |
| 46 | + return 0; |
| 47 | + Stack<String> stk = new Stack<String>(); |
| 48 | + for(String s : A ) |
| 49 | + { |
| 50 | + if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) |
| 51 | + { |
| 52 | + int b = Integer.parseInt(stk.pop()); |
| 53 | + int a = Integer.parseInt(stk.pop()); |
| 54 | + switch(s) |
| 55 | + { |
| 56 | + case "/" : stk.push( Integer.toString(a/b) ); |
| 57 | + break; |
| 58 | + case "*" : stk.push( Integer.toString(b*a) ); |
| 59 | + break; |
| 60 | + case "+" : stk.push( Integer.toString(b+a) ); |
| 61 | + break; |
| 62 | + case "-" : stk.push( Integer.toString(a-b)); |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + else |
| 67 | + { |
| 68 | + stk.push(s); |
| 69 | + } |
| 70 | + } |
| 71 | + return Integer.parseInt(stk.pop()); |
| 72 | + } |
| 73 | +} |
0 commit comments