minghxx.blog
  • [프로그래머스 / 자바] 숫자 찾기
    2023년 10월 28일 21시 54분 06초에 업로드 된 글입니다.
    작성자: 민발자
    728x90

    문제

    정수 num과 k가 매개변수로 주어질 때, num을 이루는 숫자 중에 k가 있으면 num의 그 숫자가 있는 자리 수를 return하고 없으면 -1을 return 하도록 solution 함수를 완성해보세요.

    풀이

    class Solution {
        public int solution(int num, int k) {
            int answer = 0;
            String numstr = Integer.toString(num);
            String kstr = Integer.toString(k);
    
            answer = numstr.indexOf(kstr);
            return answer == -1 ? answer : ++answer;
        }
    }

    Integer.toString() 메서드로 문자열로 변경

    indexOf() 메서드로 k 인덱스 찾기

    indexOf()는 찾는 문자가 없으면 -1 반환

    삼항연산자로 없으면 -1, 있으면 1 증가해서 리턴(인덱스가 아니라 자릿수니까!)

    728x90
    댓글