Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 8, 2015 14:46
Show Gist options
  • Save cangoal/911b4037d0850824e2ea to your computer and use it in GitHub Desktop.
Save cangoal/911b4037d0850824e2ea to your computer and use it in GitHub Desktop.
LeetCode - Evaluate Reverse Polish Notation
//
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
Stack<String> stack = new Stack<String>();
for(int i=0; i<tokens.length; i++){
String s = tokens[i];
int value1 = 0, value2 = 0, ret = 0;
switch(s){
case "+":
value1 = Integer.parseInt(stack.pop());
value2 = Integer.parseInt(stack.pop());
ret = value1 + value2;
stack.push(Integer.toString(ret));
break;
case "-":
value1 = Integer.parseInt(stack.pop());
value2 = Integer.parseInt(stack.pop());
ret = value2 - value1;
stack.push(Integer.toString(ret));
break;
case "*":
value1 = Integer.parseInt(stack.pop());
value2 = Integer.parseInt(stack.pop());
ret = value1 * value2;
stack.push(Integer.toString(ret));
break;
case "/":
value1 = Integer.parseInt(stack.pop());
value2 = Integer.parseInt(stack.pop());
ret = value2 / value1;
stack.push(Integer.toString(ret));
break;
default:
stack.push(s);
}
}
if(!stack.isEmpty()){
return Integer.parseInt(stack.pop());
} else {
return 0;
}
}
//
public int evalRPN(String[] tokens) {
if(tokens==null || tokens.length==0) return -1;
Stack<Integer> stack = new Stack<Integer>();
int ret = -1;
for(int i=0; i<tokens.length; i++){
String str = tokens[i];
if(str.equals("+")){
ret = stack.pop() + stack.pop();
stack.push(ret);
} else if(str.equals("-")){
int int1 = stack.pop();
int int2 = stack.pop();
ret = int2 - int1;
stack.push(ret);
}else if(str.equals("*")){
ret = stack.pop()*stack.pop();
stack.push(ret);
}else if(str.equals("/")){
int int1 = stack.pop();
int int2 = stack.pop();
ret = int2/int1;
stack.push(ret);
}else{
stack.push(Integer.parseInt(str));
}
}
return stack.pop();
}
//
public int evalRPN(String[] tokens) {
int returnValue = 0;
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());
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment