Obtaining maximum number via rotating digits in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a positive integer n and returns the maximum number we got doing only left rotations to the digits of the number.

Example

Following is the code −

 Live Demo

const num = 56789;
const findMaximum = (num = 1) => {
   let splitNumbers = num.toString().split("");
   let largestNumber = num;
   for(let i = 0; i < splitNumbers.length - 1; i++) {
      splitNumbers.push(splitNumbers.splice(i, 1)[0]);
      let newNumber = Number(splitNumbers.join(""));
      if(newNumber >= largestNumber) {
         largestNumber = newNumber;
      }
   };
   return largestNumber;
};
console.log(findMaximum(num));

Output

68957
raja
Updated on 17-Apr-2021 13:05:55

Advertisements