Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

解题思路:

这有一种很简单的思路:
我们无非是要判断哪个串放在哪个的前面或者后面,这其实就是两个数的比较问题,只不过大小的比较方式不是通常的形式。当然通过字符串的处理有很多的方式,不过都略显复杂了,反正两个数的比较就两种情况,所以我们不妨列拿出来比较下得出结果就行。

#coding=utf-8
class Solution:
    def cmp(self,x,y):
        if x*(10**len(str(y)))+y < y*(10**len(str(x)))+x:
            return 1
        elif x*(10**len(str(y)))+y == y*(10**len(str(x)))+x:
            return 0
        else:
            return -1
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        num.sort(self.cmp)
        return str(int(''.join(map(lambda x: str(x),num))))

相关文章:

  • 2021-08-30
  • 2021-12-02
  • 2021-05-24
  • 2022-02-18
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-24
  • 2021-09-13
  • 2021-08-07
  • 2021-12-20
  • 2021-07-05
  • 2021-08-22
相关资源
相似解决方案