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

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 19-Apr-2021 07:29:44
Advertisements