Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 15, 2015 00:51
Show Gist options
  • Select an option

  • Save dmnugent80/e8bc8b98c9f61c03df10 to your computer and use it in GitHub Desktop.

Select an option

Save dmnugent80/e8bc8b98c9f61c03df10 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Evaluation
import java.util.Stack;
public class HelloWorld
{
public static void main(String[] args)
{
String[] arr = {"4", "13", "5", "/", "+"};
Eval eval = new Eval();
int n = eval.evalRPN(arr);
System.out.println(String.format("Evaluated: %-4d", n));
}
}
// this will become its own file too (and these can be in any order)
public class Eval
{
public int evalRPN(String[] tokens) {
int retVal = 0;
Stack<String> stkNumbers= new Stack<String>();
String operators = "+-*/";
for (String s: tokens){
if (!operators.contains(s)){
stkNumbers.push(s);
}
else{
int a = Integer.valueOf(stkNumbers.pop());
int b = Integer.valueOf(stkNumbers.pop());
char c = s.charAt(0);
switch (c) {
case '+':
stkNumbers.push(String.valueOf(a + b));
break;
case '-':
stkNumbers.push(String.valueOf(b - a));
break;
case '*':
stkNumbers.push(String.valueOf(a * b));
break;
case '/':
stkNumbers.push(String.valueOf(b / a));
break;
}
}
}
retVal = Integer.valueOf(stkNumbers.pop());
return retVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment