SWEA/Intermediate

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

J_Jayce 2019. 8. 5. 12:58

문제

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

 

SW Expert Academy

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

www.swexpertacademy.com

 

 

풀이

이 문제는 스택을 이용해서 중위수식을 후위수식으로 바꾸는 과정과 후위수식으로 표현된 계산식을 계산하는 과정을 구현하는 문제였다. 이 문제는 연산자가 '+' 만 있다고 조건이 나와있었기 때문에 모든 연산자에 해당하는 범용 함수보다는 합을 구하는 함수를 구현하도록 했다.

 

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
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 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 {
                if(op.empty())
                    op.push(tmp);
                else {
                    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++) {
            int tmp = exp.charAt(i) - '0';
            if(tmp>=0 && tmp<10)
                sum.push(tmp);
            else {
                int s = 0;
                for(int j=0;j<2;j++)
                    s+=sum.pop();
                sum.push(s);
            }
        }
        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