Created
December 21, 2014 01:18
-
-
Save kanrourou/6b11c752af904f4a35de to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class Solution { | |
public int evalRPN(String[] tokens) { | |
if (tokens == null) | |
return 0; | |
Stack<Integer> stack = new Stack<Integer>(); | |
int len = tokens.length; | |
for (int i = 0; i < len; i++) { | |
String str = tokens[i]; | |
if (isOperator(str)) { | |
int num2 = stack.pop(); | |
int num1 = stack.pop(); | |
switch(str.charAt(0)) { | |
case '+': | |
stack.push(num1 + num2); | |
break; | |
case '-': | |
stack.push(num1 - num2); | |
break; | |
case '*': | |
stack.push(num1 * num2); | |
break; | |
case '/': | |
stack.push(num1 / num2); | |
break; | |
} | |
} | |
else | |
stack.push(Integer.parseInt(str)); | |
} | |
return stack.pop(); | |
} | |
private boolean isOperator(String str) { | |
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment