[SWEA] #1223 계산기2

KwonSC·2021년 11월 11일
0

SWEA - Java

목록 보기
14/26
post-thumbnail

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14nnAaAFACFAYD&categoryId=AV14nnAaAFACFAYD&categoryType=CODE


Code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Stack;
import java.util.StringTokenizer;

class Solution {
    static HashMap<Character, Integer> priority = new HashMap<Character, Integer>();
    public static void main(String args[]) throws Exception {
        priority.put('+', 1);
        priority.put('*', 2);
        priority.put('(', 0);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for (int testCase = 1; testCase <= 10; testCase++) {
            StringTokenizer st = new StringTokenizer(br.readLine(), "");
            st.nextToken();
            st = new StringTokenizer(br.readLine(), "");
            char[] infix = st.nextToken().toCharArray();
            System.out.printf("#%d %d\n", testCase, calculate(infixToPostfix(infix)));
        }
    }

    public static String infixToPostfix(char[] infix) {
        String formula = "";
        Stack<Character> stack = new Stack<>();
        for (char token : infix) {
            if (Character.isDigit(token)) {
                formula += token;
            }
            else if (token == '(') {
                stack.add(token);
            } else if (token == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    formula += stack.pop();
                }
                stack.pop();
            } else {
                while (!stack.isEmpty() && priority.get(stack.peek()) >= priority.get(token)) {
                    formula += stack.pop();
                }
                stack.push(token);
            }
        }
        while(!stack.isEmpty()) {
            formula += stack.pop();
        }
        return formula;
    }

    public static int calculate(String postfix) {
        char[] formula = postfix.toCharArray();
        Stack<Integer> stack = new Stack<>();
        for (char token : formula) {
            if (Character.isDigit(token)) {
                stack.push(Character.getNumericValue(token));
            }
            else {
                int x = stack.pop();
                int y = stack.pop();
                if (token == '+') {
                    stack.push(x + y);
                }
                else if (token == '*') {
                    stack.push(x * y);
                }
            }
        }
        return stack.pop();
    }
}

Solution

계산기1 코드로 해결하였다.
Link : https://velog.io/@kwonsc/SWEA-1222-%EA%B3%84%EC%82%B0%EA%B8%B01

0개의 댓글