blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Arranging Integers in Descending Order (12933)

The function solution receives an integer n as a parameter. Return a new integer with the digits of n arranged in descending order. For example, if n is 118372, it should return 873211.

[Programmers / JAVA] Level 1 Arranging Integers in Descending Order (12933)

The function solution receives an integer n as a parameter. Return a new integer with the digits of n arranged in descending order. For example, if n is 118372, it should return 873211.
RWB0104
@RWBwritten at 2021-12-18 11:39:02
Programmers

시리즈 모아보기

Programmers

53 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Arranging Integers in Descending Order

The function solution receives an integer n as a parameter. Return a new integer with the digits of n arranged from largest to smallest. For example, if n is 118372, it should return 873211.

  • n is a natural number between 1 and 8000000000, inclusive.
nreturn
118372873211

Arrange the integer's digits in descending order. Rather than simply reversing the digits, you need to sort them in descending order by digit value and then return them as a number again.

If you've already solved Reversing a Natural Number into an Array, this one is easy to solve.

Similarly, store each digit into an ArrayList, then sort it with Collections.sort().

Then reassemble the digits into a full number and return it. Be careful not to return it as an int.

JAVA

import java.util.ArrayList;
import java.util.Collections;

/**
 * Arranging Integers in Descending Order class
 *
 * @author RWB
 * @since 2021.12.13 Mon 19:04:28
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param n: [long] natural number
	 *
	 * @return [long] answer
	 */
	public long solution(long n)
	{
		long answer = 0;
		
		ArrayList<Integer> list = new ArrayList<>();
		
		while (n >= 10)
		{
			list.add((int) (n % 10));
			
			n /= 10;
		}
		
		list.add((int) n);
		
		Collections.sort(list);
		
		for (int i = 0; i < list.size(); i++)
		{
			answer += list.get(i) * Math.pow(10, i);
		}
		
		return answer;
	}
}
# 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