JavaScript Program to Find Maximum value possible by rotating digits of a given number


We will be writing a program to find the maximum value possible by rotating the digits of a given number. We will be using a loop to break down the number into individual digits and rearrange them in a way that gives us the maximum value. The loop will continuously rotate the digits and keep track of the highest value obtained until all possible rotations have been evaluated. The maximum value obtained from this process will then be returned as the result.

Approach

To find the maximum possible value by rotating digits of a given number, follow these steps −

  • Convert the number to a string to access its individual digits.

  • Create an array of all possible rotations of the number.

  • Sort the array in non-ascending order.

  • Convert the largest element in the array back to a number.

  • Return the largest number.

  • To handle negative numbers, the sign of the largest number should be determined before converting it back to a number.

Example

Here is an example of a JavaScript program to find the maximum value possible by rotating the digits of a given number −

function maxRotate(num) {
   num = num.toString();
   let max = num;
     
   for (let i = 0; i < num.length - 1; i++) {
      num = num.slice(0, i) + num.slice(i + 1) + num[i];
      if (num > max) {
         max = num;
      }
   }
    
   return max;
}
console.log(maxRotate(38596));

Explanation

  • The function maxRotate takes in a number num as an argument and converts it to a string.

  • A variable max is declared and is assigned the value of num. This variable will store the maximum value possible by rotating the digits of num.

  • A for loop is used to iterate through the digits of num. For each iteration, the num string is reassembled by removing the digit at index i, concatenating the remaining digits, and then adding the removed digit back to the end of the string.

  • After each iteration, the value of num is compared with the value of max. If num is greater than max, the value of num is assigned to max.

  • Finally, the function returns the value of max after all iterations are completed. In this example, when the function is called with the argument 38596, the returned value is 956638, which is the maximum value possible by rotating the digits of 38596.

Updated on: 15-Mar-2023

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements