문제 풀이/백준

[백준] 1935번. 후위 표기식2 (JAVA)

27200 2024. 2. 6. 00:00

https://www.acmicpc.net/problem/1935


문제


풀이

import java.util.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        double[] arr = new double[n];
        String s = br.readLine();

        for(int i = 0; i < n; i++){
            arr[i] = Double.parseDouble(br.readLine());
        }

        Stack<Double> stack = new Stack<>();

        for(int i = 0; i < s.length(); i++){
            char operator = s.charAt(i);
            if(operator == '+'){
                double operand2 = stack.pop();
                double operand1 = stack.pop();
                double x = operand1 + operand2;
                stack.push(x);
            }else if(operator == '-'){
                double operand2 = stack.pop();
                double operand1 = stack.pop();
                double x = operand1 - operand2;
                stack.push(x);
            }else if(operator == '/'){
                double operand2 = stack.pop();
                double operand1 = stack.pop();
                double x = operand1 / operand2;
                stack.push(x);
            }else if(operator == '*'){
                double operand2 = stack.pop();
                double operand1 = stack.pop();
                double x = operand1 * operand2;
                stack.push(x);
            }else{
                stack.push(arr[operator - 'A']);
            }
        }

        double number = stack.pop();
        System.out.printf("%.2f\n", number);
    }
}


문제를 풀 때 조건을 먼저 정확히 따지는 연습을 해야 할 것 같다. 연산자보다 알파벳이 더욱 다양한 경우가 있기에 이를 먼저 처리하고 연산자를 처리했어야 하는데 그렇지 않고 연산자를 먼저 처리하려고 하다 보니 코드에 중복되는 부분이 매우 많다.

일부로 코드를 수정하지않고 업로드하는 이유는 두고두고 보면서 코드를 짜기 전에 구조를 먼저 생각해야 한다는 것을 각인하기 위해서이다.