Rotate number to form the maximum number using JavaScript


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

Updated on: 21-Apr-2021

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements