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());
}
}
}
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 1914 하노이 탑 (0) | 2021.08.21 |
---|---|
[Algorithm] SWEA 11315 오목 판정 (0) | 2021.08.20 |
[Algorithm] 백준 2839 설탕 배달 (0) | 2021.08.20 |
[Algorithm] SWEA 1247 최적경로 (0) | 2021.08.20 |
[Algorithm] 백준 1987 알파벳 (0) | 2021.08.20 |