【问题标题】:JS How to take an array of numbers and return the largest passible combined numberJS如何取一个数字数组并返回最大的可通过组合数
【发布时间】:2019-05-22 19:16:37
【问题描述】:

此问题已被删除

【问题讨论】:

  • nums.sort(a, b) { a + b } 是无效语法,您还应该尝试返回一个值(考虑 差异,而不是 sum
  • @CertainPerformance 问题在于它是 not 无效的语法。这只是nums.sort(a, b); { a + b; } 总是使用严格模式的另一个原因,因为它实际上会抛出。
  • 为什么人们会否决这样的问题?它描述得很好,并且有完整的代码。

标签: javascript sorting numbers


【解决方案1】:

将数字传入函数,将数字拆分为单个数字,转换为整数数组,按降序排序,然后将项目连接在一起以给出返回的数字。

let numbers =[9,0,1,43,81,21,20,91,32,53,473,850,801,100,219,581,12345,12345000,1010100,8001009100]

numbers.forEach(function(number){
  console.log(myFunction(number));
})
// gives 9,0,1,43,81,21,0,91,32,53,743,850,81,100,921,851,54321,54321000,1110000,9811000000


function myFunction(num) {
  let numArray= num.toString().split('');
  numArray.forEach(function(num){
    num = parseInt(num);
  })
  numArray.sort(function(a, b){return b - a});
  return numArray.join('');
}

【讨论】:

  • @amn - 一个公平的观点 - 但由于有一个已知的数字列表,可以从中运行我包含的函数(即 - 测试参数) - 这适用于所有给定的数字.
【解决方案2】:

从一开始就有点不对劲。您的函数将整数作为参数。这意味着您不能只使用nums.sort(),因为整数没有sort() 方法,而且您真正想要做的是对单个数字进行排序。在 javascript 中,最方便的方法是转换为字符串,然后将字符串拆分为数字。

例如:

let n = 5713
let arr = n.toString().split('')

console.log(arr)

这是你现在可以排序的东西。排序后,你可以把它和join()放在一起,然后用parseInt()把它变成一个数字:

let arr = ["7", "5", "3", "1"]
let str = arr.join('')
let n = parseInt(str)

console.log(n)

您可以设置列表,即使它是字符串列表。像这样的东西:

list.sort((a, b) => b - a) // the - will convert the strings to numbers for you

b-a 将在 a > b 时返回负数,在 a sort() 回调,它是 javascript 中普遍存在的模式。

最后你可能会得到类似的结果:

function largestNumber(num) {
  let str = num.toString().split('')  // turn number into string and spilt into array
  .sort((a, b) => b - a)              // reverse sort
  .join('')                           // join back to a string

  return parseInt(str)                // return a number
  };

 console.log( largestNumber(5371))

【讨论】:

    【解决方案3】:

    /*
    E.g. if num is 23, the function should return 32.
    E.g. if num is 9, the function should return 9.
    E.g. if num is 581 the function should return 851.
    The code that I have written is this;
    */
    const sortFunc = (a, b) => { 
      if(a < b) return 1;
      if(a > b) return -1;
      return 0;
    }
    
    function largestNumber(num) {
      return (num).toString()
                    .split('')
                    .map(e => parseInt(e))
                    .sort(sortFunc);
    }
    
    console.log(largestNumber(234));
    console.log(largestNumber(184507609));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2023-03-19
      • 2016-03-11
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多