Post

[Programmers] #181944 - 홀짝 구분하기 [Java][C++][Python]

자연수 n의 홀짝을 판별해 출력하는 워밍업 문제.

[Programmers] #181944 - 홀짝 구분하기 [Java][C++][Python]

문제 링크


1. 아이디어

자연수 n을 입력받아 2로 나눈 나머지로 홀짝을 판별해, 홀수면 n is odd를 짝수면 n is even을 출력하면 되는 문제다.


2. 복잡도

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

3. 코드

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        if (n % 2 == 1) {
            System.out.println(n + " is odd");
        } else {
            System.out.println(n + " is even");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;

    if (n % 2) {
        cout << n << " is odd";
    } else {
        cout << n << " is even";
    }
}
1
2
3
4
5
6
7
8
9
10
import sys

input = sys.stdin.readline

n = int(input())

if n % 2:
    print(f"{n} is odd")
else:
    print(f"{n} is even")

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