blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 N Numbers Spaced by x (12954)

The function solution receives an integer x and a natural number n, and must return a list containing n numbers starting from x and increasing by x each time. Look at the following constraints and complete the function solution that satisfies the conditions.

[Programmers / JAVA] Level 1 N Numbers Spaced by x (12954)

The function solution receives an integer x and a natural number n, and must return a list containing n numbers starting from x and increasing by x each time. Look at the following constraints and complete the function solution that satisfies the conditions.
RWB0104
@RWBwritten at 2021-12-18 12:56:29
Programmers

시리즈 모아보기

Programmers

63 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 N Numbers Spaced by x

The function solution receives an integer x and a natural number n, and must return a list containing n numbers starting from x and increasing by x each time. Look at the following constraints and complete the function solution that satisfies the conditions.

  • x is an integer between -10000000 and 10000000, inclusive.
  • n is a natural number no greater than 1000.
xnanswer
25{ 2, 4, 6, 8, 10 }
43{ 4, 8, 12 }
-42{ -4, -8 }

We need to list n numbers spaced apart by x and return them as an array. This works fine otherwise, but the case of negative numbers is a problem.

For negative numbers, they must be sorted in descending order.

After storing the elements in an ArrayList, sort them in ascending order based on the absolute value of each number. Convert the ArrayList into a stream and use the sorted() method, overriding the sort algorithm. This can be done by overriding it with (o1, o2) -> (int) (Math.abs(o1) - Math.abs(o2)). The Math.abs() method can be used to extract the absolute value of each number.

JAVA

import java.util.ArrayList;

/**
 * N Numbers Spaced by x class
 *
 * @author RWB
 * @since 2021.12.13 Mon 22:21:01
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param x: [int] interval
	 * @param n: [int] count
	 *
	 * @return [long[]] answer
	 */
	public long[] solution(int x, int n)
	{
		ArrayList<Long> list = new ArrayList<>();
		
		while (n != 0)
		{
			list.add((long) x * n);
			
			n--;
		}
		
		return list.stream().sorted((o1, o2) -> (int) (Math.abs(o1) - Math.abs(o2))).mapToLong(Long::longValue).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