Created
May 3, 2014 11:54
-
-
Save chmllr/3090cfd4209ef4bbc00b 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
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