Finding the maximum number using at most one swap in JavaScript


We are required to write a JavaScript function that takes in a number as the first and the only argument.

The task of our function is to perform at most one swap between any two digits of the number and yield the maximum possible number. If, however, the number is already the maximum possible number we should return the number itself.

For example −

If the input number is −

const num = 1625;

Then the output should be −

const output = 6125;

We swapped 1 and 6 and this is the only swap the yields the greatest number in single swap

Example

The code for this will be −

 Live Demo

const num = 1625;
const findMaximumDigit = (num, max = 0) => {
   if(!num){
      return max;
   };
   return findMaximumDigit(Math.floor(num / 10), Math.max(max, num %10));
};
const makeOneSwap = (num = 1) => {
   let i = 0;
   const max = findMaximumDigit(num);
   const numStr = String(num);
   const numArr = numStr.split('');
   const maxIndex = numStr.lastIndexOf('' + max);
   while(i < maxIndex){
      if(+numStr[i] < max){
         let temp = numArr[i];
         numArr[i] = numArr[maxIndex];
         numArr[maxIndex] = temp;
         break;
      };
   };
   return +(numArr.join(''));
};
console.log(makeOneSwap(num));

Output

And the output in the console will be −

6125

Updated on: 03-Mar-2021

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements