Last active
July 9, 2020 16:40
-
-
Save maniish-jaiin/45923c11b0f136e52cbf041cf5b6585c 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
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