Computer >> Computer tutorials >  >> Programming >> Javascript

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 −

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