“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

6001. Minimum value for rearranging numbers

The title

Give you the integer num. Rearrange the digits in num to minimize the value and not contain any leading zeros.

Returns the smallest rearranged number without leading zeros.

Note that the symbol of num does not change after the digits are rearranged.

Example 1

Input: num = 310 Output: 103 Description: The possible combinations of digits in 310 are 013, 031, 103, 130, 301, and 310. The smallest rearranged number without any leading zeros is 103.Copy the code

Example 2

Input: num = -7605 Output: -7650 Description: -7605 digits can be arranged as -7650, -6705, -5076, and -0567. The smallest rearranged number without any leading zeros is -7650Copy the code

Answer key

simulation

Analysis of important conditions:

  • No leading zeros
  • Minimum value
  • Rearrangement of digital
  • When the numbers are rearranged, the sign does not change
  • Integer range – 1015 < = num < = 1015-10 ^ {15} < = num < = 10 ^ {15} – 1015 < = num < = 1015

Contains negative numbers; Need to categorize discussion

  • When numnumnum is a negative number, sort numnumnum from largest to smallest, convert the string to an integer, and add a sign.
  • when
    n u m num
    Phi is positive, phi is zero
    n u m num
    From small to large, we also need to classify and discuss whether there are leading zeros.

    • If there are no leading zeros, the permutation string is converted to an integer
    • With leading zeros, you need to get the first non-zero digit, swap the first non-zero digit with the first zero in the array, convert the array to a string, and return the string to an integer

Edit the code as follows:

Note:

  • Because there is no way to arrange characters directly from large to small in JavaScript, you need to convert a string to an array, call array sort to sort, and then convert an array to a string
var smallestNumber = function (num) {
  if (num === 0) return num
  let n = num
  let sign = true
  if (n < 0) {
    sign = false
    n = -n
  }
  const s = String(n).split(' ')
  if (sign) {
    const list = s.sort((a, b) = > a - b)
    let index = 0
    while (list[index] === '0') {
      index++
    }
    const t = list[index]
    list[index] = 0;
    list[0] = t
    return Number(list.join(' '))}else {
    const list = s.sort((a, b) = > b - a)
    return 0 - list.join(' ')}}Copy the code

If you have any questions, please feel free to discuss them in the comments section.