0

I have 4 digit integer number. I have to get the minimal number which is a combination of those original numbers (can't start with zeros)

function changeDigitsOrder(num){
 return Number(num.toString().split('').sort().join(''))
}

It works for numbers that doesn't have 0, but how can I get 1005 from 1500

BernaraD
  • 1
  • 1

2 Answers2

3

You could switch zeros and the following value.

function changeDigitsOrder(num) {
    return +num
        .toString()
        .split('')
        .sort((a, b) => a - b)
        .join('')
        .replace(/(0+)(.)/, '$2$1');
}

console.log(changeDigitsOrder(1500)); // 1005
console.log(changeDigitsOrder(321));  //  123
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

I played with destructuring and lookbehind

const re = /(0{0,})+([1-9]{0,})+/g;
const smallest = num => {
  let str = num.toString().split('').sort().join('')
  let [parts] = str.matchAll(re)
  let [_, zeroes, other] = parts
  return +(other.replace(/(?<=^.{1})/, zeroes))
};

console.log(smallest(1500))
console.log(smallest(1245))
console.log(smallest(5421))
console.log(smallest(421))
mplungjan
  • 155,085
  • 27
  • 166
  • 222