Return the difference between the maximum & minimum number formed out of the number n in JavaScript

We have to write a function that takes a positive number n and returns the difference between the maximum number and the minimum number that can be formed from its digits.

For example, if the number n is 203:

  • The maximum number that can be formed from its digits will be 320

  • The minimum number that can be formed from its digits will be 23 (placing the zero at one's place)

And the difference will be:

320 - 23 = 297

Therefore, the output should be 297.

Algorithm

The approach is to:

  1. Convert the number to string and split into digits
  2. Sort digits in ascending order for minimum number
  3. Sort digits in descending order for maximum number
  4. Convert back to numbers and find the difference

Example

const digitDifference = num => {
    const asc = +String(num).split("").sort((a, b) => {
        return (+a) - (+b);
    }).join("");
    const des = +String(num).split("").sort((a, b) => {
        return (+b) - (+a);
    }).join("");
    return des - asc;
};

console.log(digitDifference(203));
console.log(digitDifference(123));
console.log(digitDifference(546));
console.log(digitDifference(2354));

Output

297
198
198
3087

How It Works

Let's trace through the example with number 203:

  1. String(203).split("") gives us ["2", "0", "3"]
  2. Sorting ascending: ["0", "2", "3"] ? joins to "023" ? converts to 23
  3. Sorting descending: ["3", "2", "0"] ? joins to "320" ? converts to 320
  4. Difference: 320 - 23 = 297

Alternative Implementation

Here's a more readable version with separate functions:

function getMaxNumber(num) {
    return +String(num).split("").sort((a, b) => b - a).join("");
}

function getMinNumber(num) {
    return +String(num).split("").sort((a, b) => a - b).join("");
}

function digitDifference(num) {
    return getMaxNumber(num) - getMinNumber(num);
}

console.log(digitDifference(4021)); // 4210 - 124 = 4086
console.log(digitDifference(9876)); // 9876 - 6789 = 3087

Output

4086
3087

Conclusion

This function efficiently finds the maximum difference by sorting the digits and forming the largest and smallest possible numbers. The key insight is using JavaScript's sort method with custom comparators.

Updated on: 2026-03-15T23:18:59+05:30

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements