Skip to content

Instantly share code, notes, and snippets.

@maniish-jaiin
Last active July 9, 2020 16:30
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 maniish-jaiin/6965f4b269c02c001b15a7d5e9048215 to your computer and use it in GitHub Desktop.
Save maniish-jaiin/6965f4b269c02c001b15a7d5e9048215 to your computer and use it in GitHub Desktop.
import java.util.Stack;
class ReversePolishNotation {
public static void main(String[] args) {
System.out.println(evaluate("5 1 2 + 4 * + 3 -"));
}
public static double evaluate(String expr) {
String[] digitString = expr.split(" ");
Stack<Float> stack = new Stack<Float>();
for (String s : digitString) {
switch (s) {
case "+": {
float numberOne = stack.pop();
float numberTwo = stack.pop();
stack.push(numberOne + numberTwo);
break;
}
case "-": {
float numberOne = stack.pop();
float numberTwo = stack.pop();
stack.push(numberTwo - numberOne);
break;
}
case "*": {
float numberOne = stack.pop();
float numberTwo = stack.pop();
stack.push(numberOne * numberTwo);
break;
}
case "/": {
float numberOne = stack.pop();
float numberTwo = stack.pop();
stack.push(numberTwo / numberOne);
break;
}
default: {
stack.push(Float.parseFloat(s));
break;
}
}
}
return stack.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment