# My 3-lines code in Java and Python

• The logic is pretty straightforward. Just compare number by convert it to string.

Thanks for Java 8, it makes code beautiful.

Java:

``````public class Solution {
public String largestNumber(int[] num) {
String[] array = Arrays.stream(num).mapToObj(String::valueOf).toArray(String[]::new);
Arrays.sort(array, (String s1, String s2) -> (s2 + s1).compareTo(s1 + s2));
return Arrays.stream(array).reduce((x, y) -> x.equals("0") ? y : x + y).get();
}
}
``````

Python:

``````class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
num = [str(x) for x in num]
num.sort(cmp=lambda x, y: cmp(y+x, x+y))
return ''.join(num).lstrip('0') or '0'``````

• one line version:

``return ''.join(sorted(itertools.imap(str,num), cmp=lambda x,y:cmp(y+x, x+y))).lstrip('0') or '0'``

• It's so fantastic!

• Could you please explain more about line: cmp=lambda x, y: cmp(y+x, x+y)? Thanks so much!!

• In this case, x and y are strings, so x+y means concatenate it together, then cpm means compare them.
So we can got the result which combination have larger number.

• Thanks, xcv! Could you please show me an example like ['3', '30', '34', '5', '9']? How the cpm(y+x, x+y) works? Is cpm here a recursive call? Thanks again!

• The actual sort procedure is done by Python, the cpm just let Python know how to compare the them.

For example, if you compare '3' and '30', then the cpm will try to compare '330' and '303', then it'll decide 3 is bigger than 30 because '330' is bigger than '303'.

• I got it!! Thank you so much!!!

• big god, receive my knees... OTZ

• Good chinglish...

• Thanks . Good usage of Java 8

• @au9ustine what is the difference between itertools.imap and map?

• @SamuraiLucifer hi, I suppose you're using Python 2.x. For `itertools.imap` is something like lazy-evaluated, which could be implemented by `yield` from official docs, while `map` is something eager-evaluated. If you're using Python 3, I think it acts in same way.

• @au9ustine Your code is cool, but actually, it's not friendly

• hey there

which version of python is this? i am having 3.4 and it seems list has following method. How is num.sort(cmp = lamda x,y....) is working?

`````` |
|  sort(...)
|      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*``````

• @parvez.h.shaikh cmp() function works in python 2. In python 3.4 it is removed.

• Here is map reduce version :-) one line of code if import is ignored :P

``````class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
import functools
return functools.reduce(lambda a,b : a+b, sorted(list(map(str,nums)),cmp=lambda a,b:1 if a+b>b+a else -1 if a+b<b+a else 0, reverse=True)) if filter(None,nums) else "0"``````

• @sha256pki Nice solution. It also has a "cmp" function. Only python2 can run it!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.