Contents

Choosing a multiple of n (with.Java)

   Mar 4, 2024     2 min read

This is an article about the problem of “Selecting a multiple of n.”

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 integer n and the integer array numlist are given as parameters, complete the solution function to return an array with numbers that are not multiples of n removed from numlist.

Restrictions

  • 1 ≤ n ≤ 10,000
  • 1 ≤ size of numlist ≤ 100
  • 1 ≤ elements of numlist ≤ 100,000

Input/Output Example

nnumlistresult
3[4, 5, 6, 7, 8, 9, 10, 11, 12][6, 9, 12]
5[1, 9, 3, 10, 13, 5][10, 5]
12[2, 100, 120, 600, 12, 12][120, 600, 12, 12]

My solution to the problem

class Solution {
     public int[] solution(int n, int[] numlist) {
         int cnt = 0;
         for(int x : numlist){
             if(x % n == 0){
                 cnt++;
             }
         }
         int[] answer = new int[cnt];
         int idx = 0;
         for(int i = 0; i < numlist.length; i++){
             if(numlist[i] % n == 0){
                 answer[idx++] = numlist[i];
             }
         }
         return answer;
     }
}

Solution explanation

  • cnt: A variable for counting the number of numbers divisible by n. The initial value is set to 0.
  • for-each loop: Remove x from the numlist array one by one and repeat.
  • If the remainder when x is divided by n is 0, that is, if x is divisible by n, cnt is increased.
  • Result array (answer) initialization: Use cnt to specify the size of the result array answer.
  • Initialization of index variable (idx): Initialize the index variable idx to 0 to store the value in the result array answer.
  • for loop: Repeats the numlist array using index i.
  • If the remainder is 0 when numlist[i] is divided by n, that is, if numlist[i] is divisible by n, numlist[i] is stored in answer[idx] and idx is increased by 1.