Skip to content

Instantly share code, notes, and snippets.

@humayun0156
Created March 11, 2016 14:11
Show Gist options
  • Save humayun0156/865c32b7b50c68b3cb37 to your computer and use it in GitHub Desktop.
Save humayun0156/865c32b7b50c68b3cb37 to your computer and use it in GitHub Desktop.
import java.util.Stack;
/**
* @author humayun
*
* https://leetcode.com/problems/evaluate-reverse-polish-notation/
*
*/
public class ReversePolishNotation {
public static void main(String[] args) {
String [] tokens = new String[] {"4", "13", "5", "/", "+"}; // 4 + 13 / 5
System.out.println(new ReversePolishNotation().evalRPN(tokens));
}
public int evalRPN(String[] tokens) {
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for (String t : tokens) {
if (!operators.contains(t)) {
stack.push(t);
} else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch (t) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}
return Integer.valueOf(stack.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment