Skip to content

Instantly share code, notes, and snippets.

@BerkeSoysal
Created June 10, 2022 11:18
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 BerkeSoysal/9a76b52363319f2ce6cf5713718a9827 to your computer and use it in GitHub Desktop.
Save BerkeSoysal/9a76b52363319f2ce6cf5713718a9827 to your computer and use it in GitHub Desktop.
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String s: tokens)
{
if(s.matches("-?\\d+"))
{
stack.push(Integer.valueOf(s));
}
else
{
Integer el1 = stack.pop();
Integer el2 = stack.pop();
Integer res=0;
Operation operation = new OperationBuilder().build(el1,el2, s);
res = operation.apply();
stack.push(res);
}
}
return stack.pop();
}
enum Operand {
ADDITION("+"),
SUBTRACTION("-"),
DIVISION("/"),
MULIPLICATION("*");
private final String operationSymbol;
Operand(String operationSymbol)
{
this.operationSymbol = operationSymbol;
}
}
class OperationBuilder {
Operation build(int el1, int el2, String s)
{
if (Operand.ADDITION.operationSymbol.equals(s))
{
return new Addition(el1, el2);
}
else if (Operand.SUBTRACTION.operationSymbol.equals(s))
{
return new Subtraction(el1, el2);
}
else if (Operand.MULIPLICATION.operationSymbol.equals(s))
{
return new Multiplication(el2, el1);
}
else if (Operand.DIVISION.operationSymbol.equals(s))
{
return new Division(el1, el2);
}
return null;
}
}
abstract class Operation
{
private Integer op1;
public Integer getOp1()
{
return op1;
}
public Integer getOp2()
{
return op2;
}
private Integer op2;
public Operation(Integer op1, Integer op2)
{
this.op1 = op1;
this.op2 = op2;
}
abstract Integer apply();
}
class Addition extends Operation
{
public Addition(Integer op1, Integer op2)
{
super(op1, op2);
}
@Override
public Integer apply()
{
return getOp1() + getOp2();
}
}
class Subtraction extends Operation
{
public Subtraction(Integer op1, Integer op2)
{
super(op1, op2);
}
@Override
public Integer apply()
{
return getOp2() - getOp1();
}
}
class Multiplication extends Operation
{
public Multiplication(Integer op1, Integer op2)
{
super(op1, op2);
}
@Override
public Integer apply()
{
return getOp1() * getOp2();
}
}
class Division extends Operation
{
public Division(Integer op1, Integer op2)
{
super(op1, op2);
}
@Override
public Integer apply()
{
return getOp2() / getOp1();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment