Last active
July 9, 2020 16:30
-
-
Save maniish-jaiin/6965f4b269c02c001b15a7d5e9048215 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; | |
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