[Programmers] #120904 - 숫자 찾기 [Java][C++][Python]
정수 num의 자릿수 중 숫자 k가 처음 등장하는 위치를 1부터 세어 반환하고, 없으면 -1을 반환하는 문제.
[Programmers] #120904 - 숫자 찾기 [Java][C++][Python]
1. 아이디어
num을 10진수 문자열로 바꾼 뒤 숫자 k에 해당하는 문자가 처음 등장하는 인덱스를 찾는 문제다. 문자열 탐색이 돌려주는 0-based 인덱스에 1을 더하면 자리 번호가 되고, 찾지 못하면 -1을 반환한다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(D)$ | $O(D)$ |
($D$ = num의 자릿수, $D \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;
}
}
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;
}
1
2
3
def solution(num, k):
idx = str(num).find(str(k))
return idx + 1 if idx != -1 else -1
This post is licensed under CC BY 4.0 by the author.