Skip to content

Commit a1381fa

Browse files
committed
feat: 후위 표기법으로 작성된 수식을 계산하는 기능 예제코드 구현
1 parent 04b7ad9 commit a1381fa

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package stack;
2+
3+
public class PostCalculator {
4+
5+
public int calculate(char[] input) {
6+
Stack<Integer> stack = new ListStack<>();
7+
8+
for (char tok : input) {
9+
if (Character.isDigit(tok)) {
10+
stack.push(Character.getNumericValue(tok));
11+
} else {
12+
int op2 = stack.pop();
13+
int op1 = stack.pop();
14+
15+
switch (tok) {
16+
case '+':
17+
stack.push(op1 + op2);
18+
break;
19+
case '-':
20+
stack.push(op1 - op2);
21+
break;
22+
case '*':
23+
stack.push(op1 * op2);
24+
break;
25+
case '/':
26+
stack.push(op1 / op2);
27+
break;
28+
}
29+
}
30+
}
31+
32+
return stack.pop();
33+
}
34+
}

yoonexample/src/test/java/stack/PostCalculatorTest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package stack;
22

3+
import static org.assertj.core.api.Assertions.assertThat;
4+
35
import org.junit.jupiter.api.BeforeEach;
46
import org.junit.jupiter.api.DisplayName;
57
import org.junit.jupiter.api.Test;

0 commit comments

Comments
 (0)