304 North Cardinal St.
Dorchester Center, MA 02124

# Largest Number LeetCode Solution

## Problem – Largest Number

Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

Example 1:

``````Input: nums = [10,2]
Output: "210"``````

Example 2:

``````Input: nums = [3,30,34,5,9]
Output: "9534330"``````

Constraints:

• `1 <= nums.length <= 100`
• `0 <= nums[i] <= 109`

### Largest Number LeetCode Solution in Java

``````public class Solution {
public String largestNumber(int[] num) {
if(num == null || num.length == 0)
return "";

// Convert int array to String array, so we can sort later on
String[] s_num = new String[num.length];
for(int i = 0; i < num.length; i++)
s_num[i] = String.valueOf(num[i]);

// Comparator to decide which string should come first in concatenation
Comparator<String> comp = new Comparator<String>(){
@Override
public int compare(String str1, String str2){
String s1 = str1 + str2;
String s2 = str2 + str1;
return s2.compareTo(s1); // reverse order here, so we can do append() later
}
};

Arrays.sort(s_num, comp);
// An extreme edge case by lc, say you have only a bunch of 0 in your int array
if(s_num[0].charAt(0) == '0')
return "0";

StringBuilder sb = new StringBuilder();
for(String s: s_num)
sb.append(s);

return sb.toString();

}
}
``````

### Largest Number LeetCode Solution in C++

``````class Solution {
public:
string largestNumber(vector<int> &num) {
vector<string> arr;
for(auto i:num)
arr.push_back(to_string(i));
sort(begin(arr), end(arr), [](string &s1, string &s2){ return s1+s2>s2+s1; });
string res;
for(auto s:arr)
res+=s;
while(res[0]=='0' && res.length()>1)
res.erase(0,1);
return  res;
}
};
``````

### Largest Number LeetCode Solution in 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'``````
##### Largest Number LeetCode Solution Review:

In our experience, we suggest you solve this Largest Number LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Largest Number LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Largest Number LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions