ailen22 2024. 1. 24. 20:19

[문제]

문자열에 따라 다음과 같이 두 수의 크기를 비교하려고 합니다.

  • 두 수가 n과 m이라면
    • ">", "=" : n >= m
    • "<", "=" : n <= m
    • ">", "!" : n > m
    • "<", "!" : n < m

두 문자열 ineq와 eq가 주어집니다. ineq는 "<"와 ">"중 하나고, eq는 "="와 "!"중 하나입니다. 그리고 두 정수 n과 m이 주어질 때, n과 m이 ineq와 eq의 조건에 맞으면 1을 아니면 0을 return하도록 solution 함수를 완성해주세요.

ineq eq n m result
< = 20 50 1
> ! 41 78 0

 

 

[답]

class Solution {
    public int solution(String ineq, String eq, int n, int m) {
       // "<"일 경우
        if(ineq.equals("<")) {
        // "<="일 경우
            if (eq.equals("=")) {
            //실제로 n <= m일 경우
                if(n <= m) {
                    return 1;
            // n <= m이 아닐 경우        
                } return 0;
                
            } else {
                if(n < m) {
                    return 1;
                } return 0;
            }
          // ">"일 경우
        } else {
            if (eq.equals("=")) {
                if(n >= m) {
                    return 1;
                } return 0;
            } else {
                if(n > m) {
                    return 1;
                } return 0;
            }
        }
    }
}

하나하나 if로 비교한다, 쓰면서도 너무 헷갈리는게 큰 단점

 

 

[다른사람의 풀이]

import java.util.Map;
import java.util.function.BiFunction;

class Solution1 {
    public int solution(String ineq, String eq, int n, int m) {
        Map<String, BiFunction<Integer, Integer, Boolean>> functions = Map.of(
                ">=", (a, b) -> a >= b,
                "<=", (a, b) -> a <= b,
                ">!", (a, b) -> a > b,
                "<!", (a, b) -> a < b
        );

        return functions.get(ineq + eq).apply(n, m) ? 1 : 0;
    }
}


class Solution2 {
    public int solution(String ineq, String eq, int n, int m) {
        boolean answer = false;
        if (ineq.equals(">") && eq.equals("="))
            answer = n >= m;
        else if (ineq.equals("<") && eq.equals("="))
            answer = n <= m;
        else if (ineq.equals(">") && eq.equals("!"))
            answer = n > m;
        else 
            answer = n < m;
        return answer ? 1 : 0;
    }
}