오늘의 취준/오늘의 코테

[JAVA] 알고리즘 문제풀이 입문 5-4

gogoem 2023. 7. 10. 16:53
728x90

강의: https://inf.run/w779

 

자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비 - 인프런 | 강의

자바(Java)로 코딩테스트를 준비하시는 분을 위한 강좌입니다. 코딩테스트에서 가장 많이 출제되는 Top 10 Topic을 다루고 있습니다. 주제와 연동하여 기초문제부터 중급문제까지 단계적으로 구성

www.inflearn.com

 

 

5-4번

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

public class Main {
  public int solution(String ar){
    Stack<Integer> stack = new Stack<>();
    String[] arr = ar.split("");
    int a = 0;
    int b = 0;

    for(String x : arr){
      if(x.matches("-?\\d+")){
        stack.push(Integer.parseInt(x));
      }else{
        switch(x){
          case "+":
            a = stack.pop();
            b = stack.pop();
            stack.push(b+a);
            break;
          case "-":
            a = stack.pop();
            b = stack.pop();
            stack.push(b-a);
            break;
          case "*":
            a = stack.pop();
            b = stack.pop();
            stack.push(b*a);
            break;
          case "/":
            a = stack.pop();
            b = stack.pop();
            stack.push(b/a);
            break;
        }
      }
    }

    return stack.pop();
  }

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

    String arr = in.nextLine();
    in.close();

      System.out.print(t.solution(arr));
  }
}

 

 

>>>>>코드 정리>>>>>

 

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

public class Main {
  public int solution(String arr){
    Stack<Integer> stack = new Stack<>();
    int a = 0;
    int b = 0;

    for(char x : arr.toCharArray()){
      if(Character.isDigit(x)){
        stack.push(x-48);
      }else{
        switch(x){
          case '+':
            a = stack.pop();
            b = stack.pop();
            stack.push(b+a);
            break;
          case '-':
            a = stack.pop();
            b = stack.pop();
            stack.push(b-a);
            break;
          case '*':
            a = stack.pop();
            b = stack.pop();
            stack.push(b*a);
            break;
          case '/':
            a = stack.pop();
            b = stack.pop();
            stack.push(b/a);
            break;
        }
      }
    }

    return stack.pop();
  }

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

    String arr = in.nextLine();
    in.close();

      System.out.print(t.solution(arr));
  }
}