프로그래머스 - OX퀴즈

남궁진 (jinvicky)·2026년 4월 8일

Problem


http://school.programmers.co.kr/learn/courses/30/lessons/120907

Solution


이번에도 그림을 먼저 그려봤다.
계산식의 정답 유무에 따라서 O 또는 X를 정답 배열에 채우는 문제인데,
항상 x,y, expected가 1개로 고정되어 있어서 상대적으로 쉬운 문제다.

이들을 구분할 수 있는 것은 " "이므로 이를 구분자로 배열로 분해한 다음에 정수형으로 파싱했다.

 String[] split = quiz[i].split(" ");
 int x = Integer.parseInt(split[0]);
 int y = Integer.parseInt(split[2]);
 String oper = split[1];
 int expected = Integer.parseInt(split[4]);

배열의 길이는 문제의 길이일 것이므로 사전에 미리 선언했다.
남은 것은 연산자에 대해서 if문 분기처리를 하는 것뿐이다.

if(oper.equals("+")) {
	answer[i] = (x+y == expected) ? "O" : "X";
} else {
	answer[i] = (x-y == expected) ? "O" : "X";
}

Code


class Solution {
    public String[] solution(String[] quiz) {
        String[] answer = new String[quiz.length];
        for (int i = 0; i < quiz.length; i++) {
            String[] split = quiz[i].split(" ");
            int x = Integer.parseInt(split[0]);
            int y = Integer.parseInt(split[2]);
            String oper = split[1];
            int expected = Integer.parseInt(split[4]);
            
            if(oper.equals("+")) {
                answer[i] = (x+y == expected) ? "O" : "X";
            } else {
                answer[i] = (x-y == expected) ? "O" : "X";
            }
        }
        return answer;
    }
}
profile
문제를 차근차근 하나씩 해결하려고 합니다:)

0개의 댓글