Post

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

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

문제 링크


1. 아이디어

덧셈·뺄셈 식이 옳은지 하나씩 판정해 "O" 또는 "X"를 담는 문제다. 식의 각 토큰은 항상 공백 하나로 구분되고 음수 부호도 숫자에 붙어 있어, 공백으로 나누면 $X$, 연산자, $Y$, =, $Z$의 다섯 토큰이 나온다. 따라서 $X$와 $Y$를 연산자대로 계산한 값이 $Z$와 같은지만 비교하면 된다.


2. 코드

풀이 [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.