문제
풀이
import java.util.*;
import java.util.function.BinaryOperator;
class Solution {
private static final Map<Character, BinaryOperator<Integer>> OPERATORS;
static {
OPERATORS = new HashMap<>();
OPERATORS.put('+', (a, b) -> a + b);
OPERATORS.put('-', (a, b) -> a - b);
OPERATORS.put('*', (a, b) -> a * b);
}
public int solution(String binomial) {
String[] splitArr = binomial.split(" ");
int a = Integer.parseInt(splitArr[0]);
int b = Integer.parseInt(splitArr[2]);
char op = splitArr[1].charAt(0);
BinaryOperator<Integer> operation = OPERATORS.get(op);
if(operation == null) {
throw new IllegalArgumentException("Invalid operator: " + op);
}
return operation.apply(a, b);
}
}
Integer.parseInt(String s) | Integer.valueOf(String s) |
java.lang.Integer 클래스의 static 메서드 | |
primitive type인 int를 리턴 | 문자열을 변환하여 Integer Object를 리턴 |
출처
https://school.programmers.co.kr/learn/courses/30/lessons/181865
'Algorithm > Programmers' 카테고리의 다른 글
[Programmers] Lv.0 / rny_string / Java (1) | 2024.02.01 |
---|---|
[Programmers] Lv.0 / 문자열 바꿔서 찾기 / Java (0) | 2024.01.31 |
[Programmers] Lv.0 / 문자열 잘라서 정렬하기 / Java (0) | 2024.01.29 |
[Programmers] Lv.0 / x 사이의 개수 / Java (0) | 2024.01.26 |
[Programmers] Lv.0 / 공백으로 구분하기 2 / Java (0) | 2024.01.26 |
댓글