Created
July 31, 2021 02:42
-
-
Save sgtcortez/a521bd9cec7c36dee99e0323977c2f01 to your computer and use it in GitHub Desktop.
RPN - Reverse Polish Notation calculator
This file contains hidden or 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.*; | |
class ReversePolishCalculator { | |
interface Operation { | |
int calculate(int a, int b); | |
} | |
enum MathOperation implements Operation { | |
ADD('+') { | |
@Override | |
public int calculate(int a, int b) { | |
return a + b; | |
} | |
}, | |
SUB('-') { | |
@Override | |
public int calculate(int a, int b) { | |
return a - b; | |
} | |
}, | |
MUL('*') { | |
@Override | |
public int calculate(int a, int b) { | |
return a * b; | |
} | |
}, | |
DIV('/') { | |
@Override | |
public int calculate(int a, int b) { | |
return a / b; | |
} | |
}; | |
private final char op; | |
private MathOperation(char c) { | |
this.op = c; | |
} | |
public static MathOperation getByOp(final char op) { | |
for (final MathOperation math : values() ) { | |
if (math.op == op) return math; | |
} | |
return null; | |
} | |
} | |
final static List<String> OPS = Arrays.asList("+", "-", "*", "/"); | |
public static void main(String ... args) { | |
System.out.println(calculate("2 1 - 8 +")); // 9 | |
System.out.println(calculate("5 1 2 + 4 * + 3 -")); // 14 | |
} | |
private static int calculate(final String input) { | |
final String[] elements = input.split(" "); | |
final Stack<Integer> stack = new Stack<>(); | |
for (int index = 0; index < elements.length; index++ ) { | |
final String current = elements[index]; | |
if ( OPS.contains(current) ) { | |
// calc | |
final int right = stack.pop(); | |
final int left = stack.pop(); | |
final MathOperation math = MathOperation.getByOp(current.charAt(0)); | |
final int result = math.calculate(left, right); | |
stack.push(result); | |
} else { | |
stack.push(Integer.valueOf(current)); | |
} | |
} | |
return stack.pop(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment