SWEA/Intermediate

[SWEA] 1223. [S/W 문제해결 기본] Stack2 - 계산기2

J_Jayce 2019. 8. 5. 13:48

문제

https://www.swexpertacademy.com/main/learn/course/lectureProblemViewer.do

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

www.swexpertacademy.com

 

 

풀이

이 문제는 계산기 1 문제와 다르게 연산자가 두 개가 존재한다. 그래서 두 연산자 간의 우선순위를 정해서 후위식으로 변환해줘야 한다. 우선순위 반환 함수를 별도로 만들어주고, 후위식 변환 함수에서 스택에 있는 연산자들의 우선순위에 따라 변환될 수 있도록 구현해주었다.

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.*;
 
public class Solution {
    static Scanner scan = new Scanner(System.in);
    static Stack<Character> op = new Stack<Character>();
    static Stack<Integer> sum = new Stack<Integer>();
 
    static int get_priority(char op) {//우선순위 반환 함수
        int pri = 0;
        switch (op) {
        case '+':
            pri = 0;
            break;
        case '*':
            pri = 1;
            break;
        }
        return pri;
    }
 
    static String convert_to_post(String exp) {// 중위 -> 후위
        String post = "";
        for (int i = 0; i < exp.length(); i++) {
            char tmp = exp.charAt(i);
            if (tmp - '0' >= 0 && tmp - '0' < 10)
                post += tmp;
            else {
                while(!op.empty() && get_priority(op.peek())>=get_priority(tmp)) {
                    //우선순위가 *가 더 크기 때문에 스택에 있는 *를 먼저 처리해주기 위한 과정
                    post+=op.pop();
                }
                op.push(tmp);
            }
        }
        while (!op.empty())// 스택에 남아있는 연산자 처리
            post += op.pop();
        return post;
    }
 
    static int calc_post_exp(String exp) {// 후위식 계산
        int answer = 0;
        int n1, n2;
        for (int i = 0; i < exp.length(); i++) {
            char tmp = exp.charAt(i);
            if (tmp - '0' >= 0 && tmp - '0' < 10)
                sum.push(tmp - '0');
            else {
                switch (tmp) {
                case '+': {
                    int result = 0;
                    for (int j = 0; j < 2; j++)
                        result += sum.pop();
                    sum.push(result);
                    break;
                }
                case '*': {
                    int result = 1;
                    for (int j = 0; j < 2; j++)
                        result *= sum.pop();
                    sum.push(result);
                    break;
                }
                }
            }
        }
        answer = sum.pop();
        return answer;
    }
 
    static void solution() {
        String str = "";
        for (int i = 1; i <= 10; i++) {
            scan.nextInt();
            str = scan.next();
            System.out.println("#" + i + " " + calc_post_exp(convert_to_post(str)));
        }
    }
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        solution();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter