public class Solution { public int evalRPN(ArrayList<String> A) { Stack<Integer> stack = new Stack<Integer>(); for(String a : A){ Integer current = null; //check if current value is operand try{ current = Integer.parseInt(a); } catch(NumberFormatException e){ } if(current != null){ stack.push(current); } else{ // find last two operands int operand2 = stack.pop(); int operand1 = stack.pop(); //apply current operator on these operands int value = calculate(operand1, operand2, a); stack.push(value); } } return stack.pop(); } private int calculate(int operand1, int operand2, String a){ int result = 0; if(a.equals("+")){ result = operand1 + operand2; } else if(a.equals("")){ result = operand1  operand2; } else if(a.equals("*")){ result = operand1 * operand2; } else if(a.equals("/")){ result = operand1 / operand2; } return result; } }
Tuesday, 6 April 2021
Evaluate Reverse Polish Notation In Java
Here is a fully working Java solution for evaluation of Reverse Polish Notation (Postfix Expression). This is a common interview question that is asked in Google, Yahoo and Facebook. Solution Java class doesn't have a main() method. You can write a main() method and call evalRPN() method from there. Input argument to evalRPN() method should be a String ArrayList with valid Postfix expression.
Sample input: ["6", "1", "", "3", "*"]
Subscribe to:
Post Comments (Atom)
Evaluate Reverse Polish Notation In Java
Here is a fully working Java solution for evaluation of Reverse Polish Notation (Postfix Expression). This is a common interview question th...

Here I am just trying to explain KMP algorithm in plain english. I will also explain worst time complexity & why it is O(m + n). We will...

You already have a web property in Google Search Console. Now you try to link Google Analytics with that. But you are getting error "Yo...

If you are using JPA or Hibernate directly and got that exception while starting your application, there is one obvious reason for that. You...
No comments:
Post a comment