码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-07 23:41:46      阅读:718      评论:0      收藏:0      [点我收藏+]

标签:


英文: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); } }

 

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

标签:

原文地址:http://www.cnblogs.com/limeina/p/5469377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!