Skip to content

Instantly share code, notes, and snippets.

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