[SWEA] #1222 계산기1

KwonSC·2021년 11월 10일
0

SWEA - Java

목록 보기
13/26
post-thumbnail

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14mbSaAEwCFAYD&categoryId=AV14mbSaAEwCFAYD&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

입력값인 중위표현식을 후위표현식으로 바꿔주는 infixToPostfix()와 후위표현식을 계산해주는 calculate()로 구성되어있다. 계산기1 문제는 사실 두가지 함수 모두 필요 없지만 뒤에 문제들을 풀때 확장성을 위해서 미리 만들어서 해결하였다.
infixToPostfix는 중위표현식을 받아
1. 피연산자는 표현식에 저장
2. 연산자일때 여는 괄호면 스택에 추가
3. 연산자일때 닫는 괄호면 여는 괄호가 나올때까지 pop하여 표현식에 저장
4. 괄호가 아닌 연산자일때는 현재 연산자의 우선순위가 스택의 연산자 우선순위보다 작거나 같을때까지 pop하여 표현식에 저장후 현재 연산자를 스택에 push
calculate는 후위연산자를 입력받아 피연산자는 스택에 넣고 연산자가 나오면 스택에서 2개를 빼서 연산자에 맞는 연산을 하고 스택에 다시 넣는것을 반복, 마지막에 스택에 남은 값을 빼면 결과값이 나온다.

0개의 댓글