Skip to content

Instantly share code, notes, and snippets.

@chmllr
Created May 3, 2014 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmllr/3090cfd4209ef4bbc00b to your computer and use it in GitHub Desktop.
Save chmllr/3090cfd4209ef4bbc00b to your computer and use it in GitHub Desktop.
public class Solution {
interface Operation {public int op(int a, int b);}
class Add implements Operation{public int op(int a, int b){return a+b;}}
class Sub implements Operation{public int op(int b, int a){return a-b;}}
class Mul implements Operation{public int op(int a, int b){return a*b;}}
class Div implements Operation{public int op(int b, int a){return a/b;}}
public Operation getOp(String t) {
switch(t){
case "+": return new Add();
case "-": return new Sub();
case "*": return new Mul();
case "/": return new Div();
default: return null;
}
}
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
for(String t : tokens) {
Operation o = getOp(t);
if(o != null){
s.push(o.op(s.pop(), s.pop()));
} else {
s.push(Integer.parseInt(t));
}
}
return s.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment