Sorting an integer without using string methods and without using arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number. The function should return the smallest number that can be formed rearranging the digits of the number.

For example −

If the input number is −

const num = 614532;

Then the output should be −

const output = 123456;

The only condition is that we can neither use any String methods nor any array to store data.

Example

The code for this will be −

const num = 614532;
const sortDigits = num => {
   const getDigit = e => Math.floor(num / 10 ** e) % 10;
   const l = Math.ceil(Math.log10(num)) − 1;
   let e = l;
   while (e−−) {
      const left = getDigit(e + 1);
      const right = getDigit(e);
      if (left <= right){
         continue;
      };
      num += (right − left) * 9 * 10 ** e;
      e = l;
   };
   return num;
}
console.log(sortDigits(num));

Output

And the output in the console will be −

123456
raja
Published on 25-Nov-2020 16:32:42
Advertisements