Encountered such a problem: implement a function to find the largest integer that all numbers in the array can be spelled out. For example:

maxNum([0, 4, 19, 41, 70]) // 70441190
maxNum([3, 30, 34, 5, 9]) // 9534330
maxNum([539, 53]) // 53953
maxNum([]) // 0

renew:
The previous method is too stupid, but it is actually very simple. In the sort method, the a and b data are exchanged and combined into two numbers in sequence and subtracted.

function maxNum(nums) {
  function compare(a, b) {
    const res1 = `${a}${b}`;
    const res2 = `${b}${a}`;
    return res2 - res1;
  }
  return +nums.sort(compare).join('');
}

---------------The following is the original answer---------------

This topic is actually to sort the array, the sorting rule is to make the largest number in the high position, for example: 70 and 41 compare, 7 is greater than 4, so 70 should be placed before 41; but there are special circumstances, if two numbers What should I do if the first few digits are the same, such as 539 and 53, 5 and 3 are the same. At this time, 9 in 539 should be compared with the first digit of 53. 9 is greater than 5, so 539 should be placed first.

The implementation steps are:

  1. Convert the number into a string, compare each digit of the two numbers in turn, and put the higher digit first;
  2. If the lengths of the two numbers a and b are n and n+m respectively, and the first n digits are the same, then use a[0] and b[n] for comparison;

code show as below:

function maxNum(arr) {
  function sortFn(num1, num2) {
    num1 = `${num1}`;
    num2 = `${num2}`;
    let num1Len = num1.length;
    let num2Len = num2.length;
    let num1Index = 0;
    let num2Index = 0;

    while (1) {
      if (num1[num1Index] === num2[num2Index]) {
        num1Index++;
        num2Index++;
        // num1已遍历结束,num2未结束
        if (num1Index === num1Len && num2Index < num2Len) {
          return +num2[num2Index] - (+num1[0]);
        }
        // num2已遍历结束,num1未结束
        if (num2Index === num2Len && num1Index < num1Len) {
          return +num2[0] - (+num1[num1Index]);
        }
        // num1和num2都已遍历结束
        if (num1Index === num2Len && num2Index === num2Len) {
          return +num2[num2Index] - (+num1[num1Index]);
        }
      } else {
        return +num2[num2Index] - (+num1[num1Index]);
      }
    }
  }
  return +arr.sort(sortFn).join('');
}

Leon
1.4k 声望1k 粉丝