Computer >> Computer tutorials >  >> Programming >> Javascript

Maximum difference between a number JavaScript


We are required to write a JavaScript function that takes in a positive integer as the only input. The function should find and return the difference between that number and the smallest number that can be formed by reordering the digits of that number.

For example −

If the input number is 820

Then, the smallest number that can be formed reordering its digits is 028 = 28

And the output should be −

820 - 28 = 792

Example

const num = 820;
const maximumDifference = (num) => {
   const numStr = '' + num;
   const sorted = numStr.split('').sort();
   const smallest = +sorted.join('');
   return num -smallest;
};
console.log(maximumDifference(num));

Output

And the output in the console will be −

792