blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Array of Divisible Numbers (12910)

Write a function, solution, that returns an array of the elements in array that are evenly divisible by divisor, sorted in ascending order. If there are no elements evenly divisible by divisor, return an array containing -1.

[Programmers / JAVA] Level 1 Array of Divisible Numbers (12910)

Write a function, solution, that returns an array of the elements in array that are evenly divisible by divisor, sorted in ascending order. If there are no elements evenly divisible by divisor, return an array containing -1.
RWB0104
@RWBwritten at 2021-12-16 11:26:55
Programmers

시리즈 모아보기

Programmers

38 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Array of Divisible Numbers

Write a function, solution, that returns an array of the elements in array that are evenly divisible by divisor, sorted in ascending order. If there are no elements evenly divisible by divisor, return an array containing -1.

  • arr is an array of natural numbers.
  • For integers i and j, if i ≠ j then arr[i] ≠ arr[j].
  • divisor is a natural number.
  • array is an array of length 1 or more.
arrdivisorreturn
{ 5, 9, 7, 10 }5{ 5, 10 }
{ 2, 36, 1, 3 }1{ 1, 2, 3, 36 }
{ 3, 2, 6 }10{ -1 }

Input/Output Example #1

Among the elements of arr, the ones evenly divisible by 5 are 5 and 10. Therefore, it returns [5, 10].

Input/Output Example #2

All elements of arr are evenly divisible by 1. Sorting the elements in ascending order returns [1, 2, 3, 36].

Input/Output Example #3

3, 2, and 6 are not evenly divisible by 10. Since there are no elements that are evenly divisible, it returns [-1].

Sort the numbers in arr that are evenly divisible by divisor in ascending order and return them.

Since we don't know in advance which numbers in arr will be evenly divisible by divisor, we declare a resizable array ArrayList to hold the matching values.

Loop through arr with a for loop, dividing each element by divisor, and if it divides evenly, add it to the ArrayList. Then sort and return it.

JAVA

import java.util.ArrayList;

/**
 * Array of Divisible Numbers class
 *
 * @author RWB
 * @since 2021.12.13 Mon 14:08:59
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param arr: [int[]] array of natural numbers
	 * @param divisor: [int] the number to divide by
	 *
	 * @return [int[]] the answer
	 */
	public int[] solution(int[] arr, int divisor)
	{
		ArrayList<Integer> list = new ArrayList<>();
		
		for (int item : arr)
		{
			// If it divides evenly
			if (item % divisor == 0)
			{
				list.add(item);
			}
		}
		
		// If there are no evenly divisible numbers
		if (list.isEmpty())
		{
			list.add(-1);
		}
		
		return list.stream().sorted().mapToInt(Integer::intValue).toArray();
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08