JavaScript Coding Test Course, Sort Digits in Descending Order

Problem Definition

Resolve the following problem. You need to implement a function that sorts the given integer in descending order and returns those digits as a single integer. For example, if the input is 42145, it should return 54421.

Input

  • A single integer n (0 ≤ n ≤ 1,000,000,000)

Output

  • An integer sorted in descending order

Approach

To solve the problem, follow the steps below:

  1. Convert the given integer to a string.
  2. Convert the string to an array, containing each digit in the array.
  3. Sort the array in descending order.
  4. Combine the sorted array back into a string, then convert it to an integer and return it.

Code Implementation

Below is an example of how the above approach is implemented in code:


function sortDigitsDescending(n) {
    // Step 1: Convert the integer to a string
    const strNum = n.toString();
    
    // Step 2: Convert the string to an array
    const digitsArray = strNum.split('');
    
    // Step 3: Sort the array in descending order
    digitsArray.sort((a, b) => b - a);
    
    // Step 4: Combine the sorted array into a string and convert to integer
    const sortedNumber = parseInt(digitsArray.join(''), 10);
    
    return sortedNumber;
}

Code Explanation

The code above works as follows:

  • The function sortDigitsDescending(n) takes an integer n as a parameter.
  • It uses the toString() method to convert the number to a string.
  • The split('') method separates each digit of the string into an array.
  • The sort() method sorts the elements of the array in descending order. It compares each digit by converting them to numbers.
  • The join('') method combines the sorted array back into a single string, then parseInt() converts it to an integer and returns it.

Test Cases

Now it is necessary to validate the function with various test cases:


console.log(sortDigitsDescending(42145)); // 54421
console.log(sortDigitsDescending(123456789)); // 987654321
console.log(sortDigitsDescending(0)); // 0
console.log(sortDigitsDescending(10000)); // 10000
console.log(sortDigitsDescending(9876543210)); // 9876543210

Performance Considerations

This algorithm has a time complexity of O(n log n) depending on the length of the input. Here, n is the number of digits. During the sorting of the digits, JavaScript’s internal sorting algorithm is utilized, which guarantees O(n log n) performance in the worst case.

Conclusion

We have successfully implemented an algorithm to sort the digits of a given integer in descending order. In this process, we utilized JavaScript’s string and array methods to solve the problem simply and efficiently. An important aspect of solving algorithmic problems is to break down the problem into smaller parts and make the code writing clear at each stage. As you tackle various algorithmic problems, try to apply this approach.