How can I manipulate an array to make the largest number?

前端 未结 16 2333
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  一整个雨季
    2021-01-30 03:10

    This is my solution though it might not be efficient. The code is in python1.3

    #! /usr/bin/env python
    
    def sort(arr):
        temparr = []
        for num in arr:
            l = len(str(num)) - 1
            n = num / pow(10, 1)
            temparr.append((n, num))
        temparr.sort()
        temparr.reverse()
        return [t[1] for t in temparr]
    
    def buildNum(arr):
        finalNum = None
        for num in arr:
            snum = str(num)
            if not finalNum:
                finalNum = snum
            else:
                n1 = finalNum + snum
                n2 = snum + finalNum
                if n1 >= n2:
                    finalNum = n1
                else:
                    finalNum = n2
        return finalNum
    
    def main():
        arr = [9,1,95,17,5]
        arr = sort(arr)
        print buildNum(arr)
    main()
    

提交回复
热议问题