[Programmers] Lv0 OX 퀴즈 Java

2023. 1. 23. 16:25CS/자료구조 & 알고리즘

728x90

문제 출처

[프로그래머스 코딩 테스트 연습]

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 풀이

  • 이 문제는 형식이 고정된 식에 대해 결과가 맞는지 확인 하는 문제이다.
  • 연산 기호 숫자 사이에는 하나이상의 공백이 있으며 또한 연산이 2번이 되지 않고 1번만 된다. 또한 연산자의 수는 2개 -, + 이다.
  • 자바에서 array.split(구분자)를 쓰면 구분자를 기준으로 배열을 만들어 준다.
  • 이를 이용하면 연산자를 구분할 수 있으며(연산자의 index는 항상 1이다) 연산자에 따라 계산을 해주면 된다.

 

소스 코드

public class Solution {

    public boolean isMetodTrue(String metod) {
        String[] metodArr = metod.split(" ");
        int minusResult = Integer.parseInt(metodArr[0]) - Integer.parseInt(metodArr[2]);
        int flusResult = Integer.parseInt(metodArr[0]) + Integer.parseInt(metodArr[2]);
        return (metodArr[1].equals("-") ? minusResult : flusResult) == Integer.parseInt(metodArr[4]);
    }

    public String[] solution(String[] quiz) {

        String[] answer = new String[quiz.length];

        for (int i = 0; i < quiz.length; i++)
            answer[i] = isMetodTrue(quiz[i]) ? "O" : "X";

        return answer;
    }
}

 

728x90