Contents

Create an array1 (with.Java)

   Sep 15, 2023     2 min read

This is an article about Create an array1(with.Java)

We’re going to solve a coding test problem, and we’re going to do a retrospective on the problem we solved, as well as learn about other ways to solve it.

Let’s start with the problem

Problem

Given integers n and k, complete a solution function that returns an array that stores multiples of k in ascending order among the integers n > 1 and n < 1.

Example input and output
nkresult
103[3, 6, 9]
155[5, 10, 15]

My solution to the problem

class Solution {
    public int[] solution(int n, int k) {
        int[] answer = new int[n/k];
        int j = 0;
        for(int i = 1; i <= n; i++){
            if(i % k == 0) answer[j++] = i;
        }
        } return answer;
    }
}
solution

int[] answer = new int[n/k];: Create an integer array answer of length n/k. This array will be used to store numbers that are multiples of k.

int j = 0;: Initialize the index variable j for storing numbers in the array answer.

for(int i = 1; i <= n; i++) {: Iterate over the numbers from 1 to n, examining them.

if(i % k == 0) answer[j++] = i;: Check if the current number i is a multiple of k. If i is a multiple of k, store its value in the array answer and increment j, ready to store it at the next index.

return answer;: Returns the array answer, which finally holds the number that is a multiple of k.

This code performs the simple task of finding multiples of k within a given range and storing them in an array. The returned array stores the multiples of k in ascending order.