Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

전공공부

[BOJ_1935] 후위표기식2 본문

Study/Problem Solving

[BOJ_1935] 후위표기식2

monitor 2023. 10. 22. 20:43

설명


후위 표기식이 어떻게 동작하는지만 알면 풀기 쉽다. 4 7 2 + - 이렇게 있으면 이것은 2 + 7 하고 4 - 9 이것과 같다. 이런식으로 풀이를 해나가기 위해서는 stack을 사용해서 풀면된다. LIFO이니깐 그리고, 뺄 때 순서 바꿔서 빼는 것을 주의하면 된다.

 

 

 

코드


package Data_Structure;

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

public class BOJ_1935 {
    public static void main(String[] args) throws Exception{
        Stack<Double> st = new Stack<>();
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(in.readLine());
        String str = in.readLine();
        double ans = 0;

        double[] alpha = new double[26];

        for(int i = 0; i < N; i++){
            alpha[i] = Double.parseDouble(in.readLine());
        }

        for(char c : str.toCharArray()){
            if(c == '*'){
                    double b = st.pop();
                    double a = st.pop();
                    ans = a*b;
                    st.push(ans);
            }
            else if(c == '+'){
                    double b = st.pop();
                    double a = st.pop();
                    ans = a+b;
                    st.push(ans);
            }
            else if(c == '-'){
                    double b = st.pop();
                    double a = st.pop();
                    ans = a-b;
                    st.push(ans);

            }
            else if(c == '/'){
                    double b = st.pop();
                    double a = st.pop();
                    ans = a/b;
                    st.push(ans);
            }
            else{
                st.push(alpha[c-'A']);
            }
        }
        String str1 = String.format("%.2f", ans);
        System.out.println(str1);
    }

}
 

1935번: 후위 표기식2

첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이

www.acmicpc.net

 

'Study > Problem Solving' 카테고리의 다른 글

[BOJ_1966] 프린터 큐  (1) 2023.10.24
[BOJ_2346] 풍선 터트리기  (1) 2023.10.23
[BOJ_10866] 덱  (0) 2023.10.21
[BOJ_9012] 괄호  (1) 2023.10.21
[BOJ_2164] 카드2  (0) 2023.10.21