Given an array of integers, find the largest integer that can be concatenated from all the numbers in the array

Topic description:

Given an array of integers, find the largest integer that can be concatenated from all the numbers in the array.
For example:
input: [7,53, 54], output: 75453;
input: [1,321,35,4], output: 4353213;

Code

Ideas:

  1. Converts all numbers in the array to strings and sorts them as a whole according to the size of the first letter.
  2. If the first letters are the same, whilecompare backwards through the loop. For example, when 52 and 53 are compared, if the first letter 5 is the same, compare 2 and 3. If the lengths of the two strings to be compared are different, the first cycled string will always be Use the last letter for subsequent comparison. For example, when 523 and 52 are compared, the first two digits are the same, and the 3 of 523 is compared with the last 2 of 52, and so on.
function toInt(arr) {
    
    
	let newArr = arr.sort((a,b) => {
    
    
	  a+='';
		b+='';
		let aLen = a.length, bLen = b.length;
		let aIndex = 0, bIndex = 0;
		while(aIndex<=aLen && bIndex<bLen) {
    
    
			if(arr[aIndex]===arr[bIndex]) {
    
    
				aIndex + 1 < aLen && (aIndex++, flag=true);
				bIndex + 1 < bLen && (bIndex++, flag = true);
			} else {
    
    
				break
			}
			if(flag) break;
		}

		if(arr[aIndex]>arr[bIndex]) {
    
    
			return -1;
		} else {
    
    
			return 1;
		}
	})
	return newArr.join('')
}

おすすめ

転載: blog.csdn.net/weixin_44761091/article/details/123985575
おすすめ