Post

[Programmers] #120907 - OX퀴즈 [Java][C++][Python]

X 연산자 Y = Z 형태의 덧셈, 뺄셈 수식 문자열 배열에서 각 수식의 참, 거짓을 판별하는 문제.

[Programmers] #120907 - OX퀴즈 [Java][C++][Python]

문제 링크


1. 아이디어

각 수식 문자열은 X [연산자] Y = Z 꼴이고 토큰 사이가 공백으로 구분되므로, 공백 기준으로 잘라 두 피연산자와 연산자, 우변 값을 분리한다. 연산자가 +면 두 피연산자의 합을, -면 차를 구해 우변 값과 같은지 확인하고, 같으면 O, 다르면 X를 순서대로 담아 반환하는 문제다. 음수는 마이너스 기호가 숫자에 붙어 있어 토큰 하나로 분리되므로 정수 변환만으로 처리된다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = quiz의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public String[] solution(String[] quiz) {
        String[] ans = new String[quiz.length];

        for (int i = 0; i < quiz.length; i++) {
            String[] arr = quiz[i].split(" ");
            int x = Integer.parseInt(arr[0]);
            int y = Integer.parseInt(arr[2]);
            int z = Integer.parseInt(arr[4]);
            String op = arr[1];

            int res = op.equals("+") ? x + y : x - y;
            ans[i] = res == z ? "O" : "X";
        }

        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;

vector<string> solution(vector<string> quiz) {
    vector<string> ans;

    for (string& q : quiz) {
        stringstream ss(q);
        int x, y, z;
        char op, eq;
        ss >> x >> op >> y >> eq >> z;

        int res = op == '+' ? x + y : x - y;
        ans.push_back(res == z ? "O" : "X");
    }

    return ans;
}
1
2
3
4
5
6
7
8
9
def solution(quiz):
    ans = []

    for q in quiz:
        x, op, y, _, z = q.split()
        res = int(x) + int(y) if op == "+" else int(x) - int(y)
        ans.append("O" if res == int(z) else "X")

    return ans

This post is licensed under CC BY 4.0 by the author.