알고리즘/SwExpert recipe

SWEA 계산기2 [D4]

컵라면만두세트 2021. 2. 7. 17:09

중위식을 후위식으로 바꾸는 방법과 형변환의 필요성 

스택을 이용해서 피연산자를 넣어주는 공간과 

연산자를 넣어주는 공간 분리

package D4;

import java.util.Scanner;
import java.util.Stack;

public class 계산기2 {
	public static void swap(char [] str , int i ) {
		char temp  = str[i];
		str[i] = str[i+1];
		str[i+1] = temp;
		
	}
	// 질문할 것 후위 연산식을 보면 swap 부분을 해서 후위식으로 바꾸신거 같은데 
	// 9+5*2+1 =>95+*2+1 =>	
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		for(int tc =1; tc <= 10; tc++) {
			int n = sc.nextInt();
			char [] str = sc.next().toCharArray(); // 문자열을 char형 배열로 바꾼다 
			for(int i =0; i<n-1; i++) { // 먼저 후위식으로 바꿔줘야하니까 첫번째로 /,* 정렬해주고
				if(str[i] == '/' || str[i] == '*') {
					swap(str, i);
					i++;
				}
			}
			for(int i =0; i<n-1; i++) { // + ,- 까지 마지막으로 정렬을 해줘야 후위식으로 변하게 된다.
				if(str[i] == '+' || str[i] == '-') {
					swap(str,i);
				}
			}
			Stack<Integer> stack = new Stack<>();
			for(int i =0; i<n; i++) {
				int ans = 0;
				if(str[i] == '+') {
					stack.push(stack.pop() + stack.pop());
				}else if(str[i] == '-') {
					stack.push(stack.pop() - stack.pop());
				}else if(str[i] == '*') {
					int first = stack.pop();
					int second = stack.pop();
					ans = (second*first);
					stack.push(ans);
				}else if(str[i] == '/') {
					int first = stack.pop();
					int second = stack.pop();
					ans = (second/first);
					stack.push(ans);
			}
				else stack.push(Integer.parseInt(str[i] + ""));// 현재 str char로 받았기 때문에  string으로 형변환이된다. // parseint는 string형으로 받아야하니까 
				// toString을 이용해서 하는법, string생성자를 이용해서 하는법 , string 클래스 valueof 메메서드 이용
			}
			System.out.println("#" + tc + " " + stack.peek());
	}
	

 }
}

'알고리즘 > SwExpert recipe' 카테고리의 다른 글

SWEA 중간평균값구하기 [D2]  (0) 2021.02.08
SWEA SUM2 [D3]  (0) 2021.02.08
SWEA 평균값 구하기[D2]  (0) 2021.02.07
SWEA 쇠막대기자르기 [D4]  (0) 2021.02.06
SWEA 암호생성기 [D3]  (0) 2021.02.04