728x90
주어진 숫자에서 특정값이 첫번째로 나오는 인덱스 반환, 특정 값이 없다면 -1 반환
public int solution(int num, int k) {
int answer = -1;
char[] arr = (num+"").toCharArray();
for (int i = 0; i < arr.length; i++) {
if(arr[i]==k+'0') {
return 1+i;
}
}
return answer;
}
평소처럼 charArray로 하나하나 비교해서 k값을 만나면 그 인덱스를 반환하고 아니면 -1을 반환하게 했다.
다른 사람의 풀이를 보다가 훨씬 간결한 방법을 찾았다...
public int solution2(int num, int k) {
return ("-" + num).indexOf(k+"");
}
찾은 인덱스 값에 1을 더해주는 대신 "-"를 더하면서 동시에 문자열로 바꾸고
"k"가 있는 인덱스를 찾아 반환한다.
여기서 -1을 반환해야하는 경우가 문젠데
indexOf의 API를 찾아보면
Returns the index within this string of the first occurrence of the specified substring.
The returned index is the smallest value k for which:
this.startsWith(str, k)
If no such value of k exists, then -1 is returned.
존재하지 않을 때 -1을 반환해준단다...
'Java > Coding Test' 카테고리의 다른 글
A로 B 만들기 문제풀이 (0) | 2023.09.11 |
---|---|
팩토리얼 (0) | 2023.09.11 |
피자 나눠먹기(2) 문제풀이 (with.유클리드 호제법) (0) | 2023.09.10 |
외계행성의 나이 문제풀이 (0) | 2023.09.10 |
문자열 정렬하기(1) 문제풀이 (0) | 2023.09.10 |