Post

[Programmers] #120904 - 숫자 찾기 [Java][C++][Python]

[Programmers] #120904 - 숫자 찾기 [Java][C++][Python]

문제 링크


1. 아이디어

정수 num과 k가 주어질 때, num을 이루는 숫자 중 k가 있는지 찾는 문제다. num을 문자열로 바꾼 뒤 k에 해당하는 문자가 처음 등장하는 인덱스를 찾으면 된다.


2. 복잡도

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

($D$ = num의 자릿수 $\approx \log_{10}(\text{num})$)


3. 코드

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

1
2
3
4
5
6
class Solution {
    public int solution(int num, int k) {
        int idx = String.valueOf(num).indexOf(String.valueOf(k));
        return idx != -1 ? idx + 1 : -1;
    }
}

indexOf는 문자열이 처음 나타나는 인덱스를, 없으면 -1을 반환하는 점을 활용했다.

1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;

int solution(int num, int k) {
    int idx = to_string(num).find('0' + k);
    return idx != -1 ? idx + 1 : -1;
}

find는 문자가 처음 나타나는 인덱스를, 없으면 std::string::npos를 반환한다. npos는 -1을 size_t로 변환한 값이라, int idx로 받으면 다시 -1이 되는 점을 활용했다.

1
2
3
def solution(num, k):
    idx = str(num).find(str(k))
    return idx + 1 if idx != -1 else -1

find는 문자열이 처음 나타나는 인덱스를, 없으면 -1을 반환하는 점을 활용했다.


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