您的位置:首页 > 编程语言

[每日编程]求 largest Number - 给出一组非负整数,求这些非负整数可以拼接出的最大数字

2016-05-07 22:24 501 查看

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


中文:给出一组非负整数,求这些非负整数可以拼接出的最大数字


说明:例如,给出数组 [3, 30, 34, 5, 9],拼接出的最大数字为9534330

正确的排序方法,是使用排序方法进行比较时,比较两个字符串(设为A和B),以先后顺序拼接而成的两个字符串A+B和B+A,如果A+B更大,则A在前B在后,否则A在后B在前。

public class Solution {

public static String largestNumber(int[] nums)
{
String[] array = new String[nums.length];

for(int i = 0; i < nums.length; i++)
{
array[i] = String.valueOf(nums[i]);
}

String temp;
for(int i = 0; i < array.length; i++)
{
for(int j = i+1; j < array.length; j++)
{
if((array[i] + array[j]).compareTo(array[j] + array[i]) < 0)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}

if(array[0].equals("0"))
return "0";
else
{
return String.join("", array);
}
}

public static void main(String[] args)
{
int[] nums = {3, 30, 34, 5, 9};

String largestNum = largestNumber(nums);

System.out.println(largestNum);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: