본문 바로가기
Algorithm/Programmers

[Programmers] Lv.0 / 간단한 식 계산하기 / Java

by unknownomad 2024. 1. 30.

문제

 

풀이

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

댓글