코딩 테스트/5. Stack, Queue

Q5 -4 후위식 연산(postfix)

길동이이이잉 2021. 9. 23. 23:23
728x90
반응형

4. 후위식 연산(postfix)

 

* 설명

후위연산식이 주어지면 연산한 결과를 출력하는 프로그램을 작성하세요.

만약 3*(5+2)-9 을 후위연산식으로 표현하면 352+*9- 로 표현되며 그 결과는 12입니다.

 

* 입력

첫 줄에 후위연산식이 주어집니다. 연산식의 길이는 50을 넘지 않습니다.

식은 1~9의 숫자와 +, -, *, / 연산자로만 이루어진다.

 

* 출력

연산한 결과를 출력합니다.

 

* 예시 입력 1 

352+*9-

* 예시 출력 1

12

 

 

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

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String in1 = in.nextLine();
		
		Stack<Integer> num = new Stack<Integer>();
		
		for(char x : in1.toCharArray()) {
			if(Character.isDigit(x) == false) {///연산자일 경우
				int tmp1 = num.pop();
				int tmp2 = num.pop();
				int res = 0;
				if(x == '+') res = tmp2+tmp1;
				else if(x == '-') res = tmp2-tmp1;
				else if(x == '*') res = tmp2*tmp1;
				else if(x == '/') res = tmp2/tmp1;
				
				num.push(res);				
			}else {///숫자일 경우
				num.push(Character.getNumericValue(x));
			}
		}
		
		System.out.print(num.pop());
		in.close();
		return;

	}

}

 

 

 

import java.util.*;
class Main {	
	public int solution(String str){
		int answer=0;
		Stack<Integer> stack = new Stack<>();
		for(char x : str.toCharArray()){
			if(Character.isDigit(x)){
				stack.push(x-48);
			}
			else{
				int rt=stack.pop();
				int lt=stack.pop();
				if(x=='+') stack.push(lt+rt);
				else if(x=='-') stack.push(lt-rt);
				else if(x=='*') stack.push(lt*rt);
				else if(x=='/') stack.push(lt/rt);
			}
		}
		answer=stack.get(0);
		return answer;
	}
	public static void main(String[] args){
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str=kb.next();
		System.out.println(T.solution(str));
	}
}
728x90
반응형