Finding the immediate bigger number formed with the same digits in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should rearrange the digits of the numbers such that we form the smallest number using the same digits but just bigger than the input number.

For instance, if the input number is 112. Then the output should be 121.

Example

Following is the code −

 Live Demo

const num = 112;
const findNextBigger = (num = 1) => {
   const sortedDigits = (num = 1) => {
      return String(num)
      .split('')
      .sort((a, b) => b - a);
   };
   let max = sortedDigits(num).join('');
   max = Number(max);
   for(let i = num + 1; i <= max; i++){
      if(max === +sortedDigits(i).join('')){
         return i;
      };
   };
   return -1;
};
console.log(findNextBigger(num));

Output

Following is the console output −

121

Updated on: 19-Apr-2021

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements