-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathLargest Number.py
52 lines (41 loc) · 1.18 KB
/
Largest Number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
Given a list of non negative integers, arrange them such that they form the largest number.
Example
Given [1, 20, 23, 4, 8], the largest formed number is 8423201.
"""
__author__ = 'Daniel'
class Solution:
def largestNumber(self, nums):
"""
Start off by enumerate simple examples
Compare digit by digit
The comparator is the core.
:type nums: list[int]
:rtype: str
"""
nums = map(str, nums)
nums.sort(cmp=self.cmp, reverse=True)
nums = "".join(nums)
nums = nums.lstrip("0")
if not nums:
nums = "0"
return nums
def cmp(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
order = 1
if len(a) > len(b):
order = -1
a, b = b, a
for i in xrange(len(a)):
if int(a[i]) != int(b[i]):
return order*(int(a[i])-int(b[i]))
if len(a) == len(b):
return 0
return order*self.cmp(a, b[len(a):])
if __name__ == "__main__":
assert Solution().largestNumber([0, 0]) == "0"
assert Solution().largestNumber([1, 20, 23, 4, 8]) == "8423201"