Finding the just bigger number formed by same digits in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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

Our function should find and return a number such that it contains only and all the digits of the input number and is just bigger than the input number

If there exists no such number, our function should return -1.

For example, if the input to the function is −

const num = 5656;

Then the output should be −

const output = 5665;

Output Explanation

Because 5665 contains only and all digits of 5656 and is just greater than 5656.

Example

Following is the code &mius;

 Live Demo

const num = 5656;
const justBigger = (num) => {
   const sorted = num => ('' + num).split('').sort((a, b) => b - a);
   const max = +sorted(num).join('')
   for (let i = num + 1; i <= max; i++) {
      if (max === +sorted(i).join('')){
         return i;
      }
   };
   return -1;
}
console.log(justBigger(num));

Output

Following is the console output −

5665
raja
Published on 21-Apr-2021 12:57:35
Advertisements