Contents

Doubling an Array (with.Java)

   Dec 20, 2023     1 min read

This is the “Doubling an Array” problem.

We’re going to learn by solving coding test questions, looking back at the problems we solved, and exploring other ways to solve them.

Let’s start with the problem

The problem

An array of integers, numbers, is given as a parameter.

Complete the solution function so that it returns an array with twice as many elements as each element in numbers.

Example input and output

numbersresult
[1, 2, 3, 4, 5][2, 4, 6, 8, 10]
[1, 2, 100, -99, 1, 2, 3][2, 4, 200, -198, 2, 4, 6]

My solution to the ### problem

class Solution {
    public int[] solution(int[] numbers) {
        for(int i = 0; i < numbers.length; i++){
            numbers[i] *= 2;
        }
    } return numbers;
}

solution description

public int[] solution(int[] numbers) : Declares a function solution and takes an integer array numbers as an input parameter. The function returns an array of integers.

for(int i = 0; i < numbers.length; i++){: Starts a loop to access each element of the array numbers. The variable i represents the index in the array through the iteration.

numbers[i] *= 2;: Doubles the array element corresponding to the current index i. This code modifies the value of the current array element by multiplying it by 2.

}: Marks the end of the loop. It exits after all elements of the array have been processed.

return numbers;: Returns the modified array numbers as the return value of the function. So, this function doubles all the elements of the given array and returns the result.