[프로그래머스] Lv.0 간단한 식 계산하기

이다혜·2023년 10월 31일
0

프로그래머스

목록 보기
37/61
post-thumbnail

📎 문제 출처


https://school.programmers.co.kr/learn/courses/30/lessons/181865

📌 문제 설명


문자열 binomial이 매개변수로 주어집니다. binomial은 "a op b" 형태의 이항식이고 a와 b는 음이 아닌 정수, op는 '+', '-', '*' 중 하나입니다. 주어진 식을 계산한 정수를 return 하는 solution 함수를 작성해 주세요.

❓ 풀이 방법


문자열을 공백을 기준으로 분리하면 [숫자, 연산자, 숫자] 형태로 나누어진다. 연산자를 기준으로 switch문을 사용해서 연산 결과를 계산한다.

📌 Code


class Solution {
    public int solution(String binomial) {
        String[] binomialBits = binomial.split(" ");
        
        int num1 = Integer.parseInt(binomialBits[0]);
        int num2 = Integer.parseInt(binomialBits[2]);
        String op = binomialBits[1];
        
        int answer = switch (op) {
            case "+":
                yield num1 + num2;
            case "-" :
                yield num1 - num2;
            case "*" :
                yield num1 * num2;               
        default:
                throw new IllegalArgumentException("Invalid operator: " + op);
        };
        
        return answer;
    }
}

0개의 댓글