https://school.programmers.co.kr/learn/courses/30/lessons/181865
문자열 binomial이 매개변수로 주어집니다. binomial은 "a op b" 형태의 이항식이고 a와 b는 음이 아닌 정수, op는 '+', '-', '*' 중 하나입니다. 주어진 식을 계산한 정수를 return 하는 solution 함수를 작성해 주세요.
문자열을 공백을 기준으로 분리하면 [숫자, 연산자, 숫자] 형태로 나누어진다. 연산자를 기준으로 switch문을 사용해서 연산 결과를 계산한다.
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;
}
}