# Leetcode 179: largest number

Leetcode 179: largest number

https://leetcode.com/problems/largest-number/

1, what is the largest number looks like?

2, how to make the arrangement in order to make the number large?
example:
1,2,5,34,36 –> 1243436, 5363421

3, the first idea is do the comparation carefully
1) find the largest highest digit in all numbers (may not find the final largest number) : 9123, 89, 77,
2) if there is two same largest digits, compare them and find the second largest digit in the two numbers
3) may use string comparation
String.sort()
Then I come up code like this:

public static String largestNumber(int[] nums) {
String[] a = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
a[i] = nums[i] + "";
}
Arrays.sort(a, Collections.reverseOrder());
String res = "";
for (String num : a) {
res += num;
}
return res;
}

4, when I finish the code, I found my solution cannot pass the test case: [121, 12]
1) there two possible arrangement: 12112, 12121
2) if we chose string comparation, the largest number should be 121, and the smaller would be 12
3) that means, if two numbers first few digits are same,
for example: 886,88,
we need to check other numbers in the nums[],
if there is 7x.. we need to chose 887x.. instead of 886..

5, So the custom comparation has some problems:
it need to compare the sum of the different arrangement of the two numbers:
for example: 121 and 12
we need to compare 12112 and 12121
Another exmaple: 98 and 999
we need to compare 98999 and 99998

6, the final code would be a little change:

public String largestNumber(int[] nums) {
String[] a = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
a[i] = nums[i] + "";
}
Arrays.sort(a,(str1,str2) -> (str2 + str1).compareTo(str1 + str2));
if(a[0].equals("0")) return "0";
String res = "";
for (String num : a) {
res += num;
}
return res;
}
• 本文已收录于以下专栏：

## [LeetCode]179.Largest Number

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

## Leetcode 179. Largest Number

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

## <LeetCode OJ> 179. Largest Number

179. Largest Number My Submissions Question Total Accepted: 37152 Total Submissions: 208760 Diff...

## leetcode179. Largest Number

179. Largest NumberGiven a list of non negative integers, arrange them such that they form the large...

## LeetCode 179. Largest Number

LeetCode 179. Largest Number 给出一个非负整型列表，对列表里的整型进行排序，使得排序后将这些数字连在一起的数字最大。...
• luzheqi
• 2016年11月08日 11:42
• 199

## Leetcode.179 Largest Number

Problem description : Given a list of non negative integers, arrange them such that they form the l...

举报原因： 您举报文章：Leetcode 179: largest number 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)