Skip to content

Commit 90c8bf6

Browse files
committed
feat: 후위 연산식을 계산하는 클래스 구현
1 parent a7ed919 commit 90c8bf6

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.wonu606.calculator.calculator;
2+
3+
import java.util.List;
4+
5+
public interface Calculator {
6+
7+
double calculate(List<String> expression);
8+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.wonu606.calculator.calculator;
2+
3+
import com.wonu606.calculator.model.Operator;
4+
import java.util.ArrayDeque;
5+
import java.util.Deque;
6+
import java.util.List;
7+
import java.util.Objects;
8+
9+
public class PostfixCalculator implements Calculator {
10+
11+
@Override
12+
public double calculate(List<String> postfixExpression) {
13+
Deque<Double> operandStack = new ArrayDeque<>();
14+
15+
for (String token : postfixExpression) {
16+
handleToken(operandStack, token);
17+
}
18+
19+
return operandStack.pop();
20+
}
21+
22+
private void handleToken(Deque<Double> operandStack, String token) {
23+
if (isOperator(token)) {
24+
Operator operator = Objects.requireNonNull(Operator.get(token));
25+
performOperation(operandStack, operator);
26+
} else {
27+
operandStack.push(Double.valueOf(token));
28+
}
29+
}
30+
31+
private void performOperation(Deque<Double> operandStack, Operator operator) {
32+
double secondOperand = operandStack.pop();
33+
double firstOperand = operandStack.pop();
34+
35+
double result = operator.apply(firstOperand, secondOperand);
36+
operandStack.push(result);
37+
}
38+
39+
private boolean isOperator(String token) {
40+
return Operator.get(token) != null;
41+
}
42+
}

0 commit comments

Comments
 (0)