关于javascript:求数组中所有数字可拼出的最大整数

遇到这样一个题:实现一个函数,求数组中所有数字可拼出的最大整数。举例:

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

这个题目实际上是对数组进行排序,排序的规定是让最大的数字排在高位,比方:70和41比拟,7大于4,所以70应该放在41前;然而有非凡状况,如果两个数字前几位都雷同该怎么办,比方539和53,5和3都雷同,此时应该用539中的9和53的第一位5比拟,9大于5,所以539应该放在后面。

实现的步骤为:

  1. 将数字转为字符串,顺次比拟两个数字的每一位,将高位更大的数字排在后面;
  2. 如果两个数字 a, b 的长度别离为 n 和 n+m,且前 n 位都雷同,那么用 a[0] 和 b[n] 进行比拟;

代码如下:

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('');
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理