Created
March 11, 2016 14:11
-
-
Save humayun0156/865c32b7b50c68b3cb37 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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