본문으로 바로가기

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14nnAaAFACFAYD 

 

SW Expert Academy

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

swexpertacademy.com

 


 

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

public class Solution_SWEA_1223_계산기2 {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		for (int t = 1; t <= 10; t++) {
			int N = Integer.parseInt(br.readLine()); // 테스트 케이스의 길이
			String formula = br.readLine();
			String postfix = "";
			Stack<Character> operator = new Stack<>();
			
			for (int i = 0; i < formula.length(); i++) {
				if (formula.charAt(i) != '*' && formula.charAt(i) != '+') postfix += formula.charAt(i);// 피연산자인 경우
				else {
					if (operator.isEmpty() || formula.charAt(i) == '*')	operator.push(formula.charAt(i));
					else {
						while (!operator.isEmpty() && operator.peek() != '+')	postfix += operator.pop();
						operator.push(formula.charAt(i));
					}
				}
			}
			while (!operator.isEmpty())	postfix += operator.pop();

			Stack<Integer> operand = new Stack<>(); // 피연산자
			
			for (int i = 0; i < postfix.length(); i++) {
				if (postfix.charAt(i) != '*' && postfix.charAt(i) != '+')	operand.push(postfix.charAt(i)-'0'); // 피연산자인 경우
				else { // 연산자인 경우
					if (postfix.charAt(i) == '+')	operand.push(operand.pop() + operand.pop());
					else	operand.push(operand.pop() * operand.pop());
				}
			}
			
			System.out.println("#" + t + " " + operand.pop());
		}
	}
}