본문으로 바로가기

[알고리즘]후위연산자(Postfix)

category Algorithm/Stack, Queue 2021. 10. 26. 18:56
728x90
반응형

▷ 문제

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

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

* 입력

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

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

* 출력

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

▷ 입력 예시

352+*9-

▷ 출력 예시

12

▷ 풀이

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

public class Main {	
    public int solution(String str){
      int answer = 0;
      Stack<Integer> stack = new Stack<Integer>();

      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 boolean isOperator(char x){
      if(x == '+' || x == '-' || x == '*' || x == '/' || x == '%'){
        return true;
      }
      return false;
    }

    public static void main(String[] args){
        Main main = new Main();
        Scanner kb = new Scanner(System.in);

        String str = kb.next();

        kb.close();

        System.out.println(main.solution(str));
    }
  }

▷ 핵심 포인트

1. 후위수식을 이해하고 계산할 수 있어야 구현할 수 있습니다.

반응형