Find Immediate Bigger Number with 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: 2021-04-19T07:30:18+05:30

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements