Post

[Programmers] #181921 - 배열 만들기 2 [Java][C++][Python]

[Programmers] #181921 - 배열 만들기 2 [Java][C++][Python]

문제 링크


1. 아이디어

$l$부터 $r$까지 수를 하나씩 보며 모든 자리가 0 또는 5인 것만 모은다. 작은 수부터 보므로 모은 순서가 그대로 오름차순이다.


2. 코드

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;

class Solution {
    public int[] solution(int l, int r) {
        List<Integer> list = new ArrayList<>();
        for (int i = l; i <= r; i++) {
            if (hasOnly0And5(i)) list.add(i);
        }

        if (list.isEmpty()) return new int[]{-1};
        return list.stream().mapToInt(Integer::intValue).toArray();
    }

    static boolean hasOnly0And5(int x) {
        while (x > 0) {
            int d = x % 10;
            if (d != 0 && d != 5) return false;
            x /= 10;
        }

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

bool has_only_0_and_5(int x) {
    while (x > 0) {
        int d = x % 10;
        if (d != 0 && d != 5) return false;
        x /= 10;
    }

    return true;
}

vector<int> solution(int l, int r) {
    vector<int> v;
    for (int i = l; i <= r; i++) {
        if (has_only_0_and_5(i)) v.push_back(i);
    }

    if (v.empty()) return {-1};
    return v;
}
1
2
3
4
5
6
7
def has_only_0_and_5(x):
    return all(c in "05" for c in str(x))


def solution(l, r):
    ans = [x for x in range(l, r + 1) if has_only_0_and_5(x)]
    return ans if ans else [-1]

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