Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 21, 2014 01:18
Show Gist options
  • Save kanrourou/6b11c752af904f4a35de to your computer and use it in GitHub Desktop.
Save kanrourou/6b11c752af904f4a35de to your computer and use it in GitHub Desktop.
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