Skip to content

Commit 66eaa90

Browse files
authoredApr 24, 2023
[백준 1935] 후위 표기식2 - 자료구조
1 parent 1c45068 commit 66eaa90

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
 

‎chanwoo/week02/후위표기식2.java

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import java.io.BufferedReader;
2+
import java.io.BufferedWriter;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.io.OutputStreamWriter;
6+
import java.util.Stack;
7+
8+
/**
9+
* 1935번
10+
*/
11+
public class Main {
12+
13+
private static final Stack<Character> operationStack = new Stack<>();
14+
private static final Stack<Double> operandStack = new Stack<>();
15+
public static final int CHARACTER_A_ASCII_CODE = 65;
16+
17+
public static void main(String[] args) throws IOException {
18+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
19+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
20+
21+
int n = Integer.parseInt(br.readLine());
22+
int[] value = new int[n];
23+
String postfixExpression = br.readLine();
24+
25+
for (int i = 0; i < n; i++) {
26+
value[i] = Integer.parseInt(br.readLine());
27+
}
28+
29+
for (int i = 0; i < postfixExpression.length(); i++) {
30+
char bitOfExpression = postfixExpression.charAt(i);
31+
if (isOperation(bitOfExpression)) {
32+
operationStack.push(bitOfExpression);
33+
calculate();
34+
continue;
35+
}
36+
operandStack.push((double) value[bitOfExpression - CHARACTER_A_ASCII_CODE]);
37+
}
38+
39+
Double result = operandStack.pop();
40+
bw.write(String.format("%.2f", result));
41+
bw.flush();
42+
bw.close();
43+
}
44+
45+
public static boolean isOperation(char bit) {
46+
if (Character.isAlphabetic(bit)) {
47+
return false;
48+
}
49+
return true;
50+
}
51+
52+
public static void calculate() {
53+
Double rightOperand = operandStack.pop();
54+
Double leftOperand = operandStack.pop();
55+
Character operation = operationStack.pop();
56+
57+
double result = operate(leftOperand, rightOperand, operation);
58+
operandStack.push(result);
59+
}
60+
61+
private static double operate(Double leftOperand, Double rightOperand, Character operation) {
62+
switch (operation) {
63+
case '+': {
64+
return leftOperand + rightOperand;
65+
}
66+
case '-': {
67+
return leftOperand - rightOperand;
68+
}
69+
case '*': {
70+
return leftOperand * rightOperand;
71+
}
72+
case '/': {
73+
return leftOperand / rightOperand;
74+
}
75+
}
76+
return 0;
77+
}
78+
}

0 commit comments

Comments
 (0)
Please sign in to comment.