Skip to content

Instantly share code, notes, and snippets.

@maniish-jaiin
Last active July 9, 2020 16:47
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/7249ab50819d0988dd61dd757491ec1d to your computer and use it in GitHub Desktop.
Save maniish-jaiin/7249ab50819d0988dd61dd757491ec1d to your computer and use it in GitHub Desktop.
import java.util.HashMap;
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<>();
HashMap<String, BiFunction<Float, Float, Float>> map = constructMapForOperator();
for (String s : digitString) {
if (map.containsKey(s)) stack.push(operate(map.get(s), stack));
else stack.push(Float.parseFloat(s));
}
return stack.pop();
}
private static HashMap<String, BiFunction<Float, Float, Float>> constructMapForOperator() {
HashMap<String, BiFunction<Float, Float, Float>> map = new HashMap();
map.put("+", (a, b) -> a + b));
map.put("-", (a, b) -> a - b);
map.put("*", (a, b) -> a * b);
map.put("/", (a, b) -> a / b);
return map;
}
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