Rotate number to form the maximum number using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number n. Our function is required to return the maximum value by rearranging its digits.

Example

Following is the code −

const num = 124;
const rotateToMax = n => {
   n = n
      .toString()
      .split('')
      .map(el => +el);
      n.sort((a, b) =>
      return b - a;
   });
   return n
   .join('');
};
console.log(rotateToMax(num));

Output

421
raja
Published on 21-Apr-2021 06:58:28
Advertisements