Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
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
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[SW Expert Academy] 1224. [S/W 문제해결 기본] 6일차 - 계산기3 본문

SW_Expert

[SW Expert Academy] 1224. [S/W 문제해결 기본] 6일차 - 계산기3

코드와이 2021. 2. 15. 22:07

 

문제링크

swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=4&contestProbId=AV14tDX6AFgCFAYD&categoryId=AV14tDX6AFgCFAYD&categoryType=CODE&problemTitle=&orderBy=PASS_RATE&selectCodeLang=JAVA&select-1=4&pageSize=10&pageIndex=1

 

SW Expert Academy

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

swexpertacademy.com

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer st;
	static StringBuilder sb = new StringBuilder();
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		
		for(int tc = 1 ; tc <= 10 ; tc++) {
			sb.append("#" + tc + " ");
			
			int T = Integer.parseInt(br.readLine());
			
			char[] str = br.readLine().toCharArray();
			ArrayList<Character> str2 = new ArrayList<Character>();
			Stack<Character> s = new Stack<>();
			
			for(char c : str) {
				if (c != '+' && c!= '*' && c != '(' && c != ')') {
					str2.add(c);
				}
				else if(c == '+') {
					while( s.size() != 0 && s.peek() != '(') {
						str2.add(s.pop());
					}
					s.add(c);
				}
				else if(c == '*') {
					while( s.size() != 0 && s.peek() == '*') {
						str2.add(s.pop());
						}
					s.add(c);
				}
				else if(c == '(') {
					s.add(c);
				}
				else if(c == ')') {
					while(s.peek() != '(') {
						str2.add(s.pop());
					}
					s.pop();
				}
			}
			while(s.size() != 0) {
				str2.add(s.pop());
			}
			Stack<Integer> ans = new Stack<>();
			
			for(char c : str2) {
				if (c != '+' && c!= '*') {
					ans.add(c - '0');
				}
				else {
					int a = ans.pop();
					int b = ans.pop();
					int d;
					if( c == '+' ) d = a + b;
					else d = a*b;
					ans.add(d);
				}
			}
			
			sb.append(ans.pop());
			
			System.out.println(sb);
			sb.setLength(0);
		}
	}
}