Skip to content

Sort a Java Integer in Descending Order

The challenge

Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.

Examples:

Input: 42145 Output: 54421

Input: 145263 Output: 654321

Input: 123456789 Output: 987654321

Test cases

import org.junit.Test; import static org.junit.Assert.assertEquals; public class DescendingOrderTest { @Test public void test_01() { assertEquals(, DescendingOrder.sortDesc()); } @Test public void test_02() { assertEquals(51, DescendingOrder.sortDesc(15)); } @Test public void test_03() { assertEquals(987654321, DescendingOrder.sortDesc(123456789)); } }
Code language: Java (java)

The solution in Java

public class DescendingOrder { public static int sortDesc(final int num) { // return if a negative number if (num<) return num; // our number we will return int sortedNumber = ; // loop with a maximum number int // perform loop in reverse for (int i = 9; i >= ; i--) { // set a local number variable int tmpNumber = num; // while greater than 0 while (tmpNumber > ) { // get the digit int digit = tmpNumber % 10; // check for the greatest digit in the given number if (digit == i) { // build the sortedNumber value sortedNumber *= 10; sortedNumber += digit; } // reduce the loop variable tmpNumber /= 10; } } // return our sorted number return sortedNumber; } }
Code language: Java (java)

See also  [Solved] Error - The following untracked working tree files would be overwritten by merge
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x