Contents

Finding numbers (with.Java)

   Mar 3, 2024     2 min read

This is an article about the “Find a number” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When the integers num and k are given as parameters, if there is k among the numbers making up num, complete the solution function so that it returns the number of digits in num, and if not, it returns -1.

Restrictions

  • 0 < num < 1,000,000
  • 0 ≤ k < 10
  • If there are multiple k in num, the first occurrence is returned.

Input/Output Example

numkresult
2918313
23244344
1234567-1

My solution to the problem

import java.util.Arrays;

class Solution {
     public int solution(int num, int k) {
         int answer = 0;
         char[] chArr = String.valueOf(num).toCharArray();
         char chK = (char) (k + '0');

         for(int i = 0; i < chArr.length; i++){
             if(chArr[i] == chK){
                 answer = i + 1;
                 break;
             }
         }
         if(answer == 0) answer = -1;
         return answer;
     }
}

Solution explanation

  • Initialize the answer variable to 0. This variable serves to store the position where k first appears.
  • After converting num to String, use the toCharArray() method to convert each digit into a char array.
  • The value converted from k to char is stored in the chK variable.
  • Use a for statement to traverse the chArr array and check if there is a number equal to chK.
  • If chArr[i] and chK are the same, the value of i + 1 is stored in the answer and the loop is terminated. At this time, i + 1 means the position starting from 1.
  • After the loop ends, if the answer is 0, -1 is stored because k is not in the given number.
  • Finally, the answer value is returned.