본문 바로가기
알고리즘/백준

(백준/자바) 힌트문제2 03. 구현 - 백준 5613번 문제 : 계산기 프로그램

by son_i 2023. 7. 25.
728x90

5613번: 계산기 프로그램 (acmicpc.net)

 

5613번: 계산기 프로그램

입력의 각 줄에는 숫자와 +, -, *, /, =중 하나가 교대로 주어진다. 첫 번째 줄은 수이다. 연산자의 우선 순위는 생각하지 않으며, 입력 순서대로 계산을 하고, =가 주어지면, 그때까지의 결과를 출

www.acmicpc.net

주어지는 수와 계산 결과가 int형으로 충분히 될 거라고 생각했다.

queue와 stack을 이용해서 풀었다.

q에 =을 제외한 모든 피연산자와 연산자를 담아놓고

q에서 하나씩 빼면서 진행.

피연산자라면 stack에 push, 연산자면 stack에서 pop하는데 중위연산이므로 stack에는 하나의 숫자밖에 들어있지않음

그래서 stack.pop 하나, q.poll하나 이렇게 피연산자를 두 개 구해서 연산자에 따른 연산 진행후 stack에 다시 push해줘야함.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Realize_03 {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Queue<String> q = new LinkedList<>();
        Stack<Integer> stack = new Stack();
        String str = br.readLine();
        while(!str.equals("=")){
            q.add(str);
            str = br.readLine();
        }
        while(!q.isEmpty()){
            String s = q.poll();
            if(s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*")){
                int num1 = stack.pop();
                int num2 = Integer.parseInt(q.poll());

                if(s.equals("+")){
                    stack.push(num1 + num2);
                }
                else if(s.equals("-")){
                    stack.push(num1 - num2);
                }
                else if (s.equals("*")){
                    stack.push(num1 * num2);
                } else{
                    stack.push(num1 / num2);
                }
            } else {
                stack.push(Integer.parseInt(s));
            }
        }
        System.out.println(stack.pop());
    }
}