LeetCode——Largest Number
Description:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Note: The result may be very large, so you need to return a string instead of an integer.
把所给的数字排列成最大的数,首先想到的思路是按位比较,但是那样比较麻烦而且容易出BUG,所以还有一种简单的思路就是在排序的时候比较两种情况前后排列取结果最大的那种顺序。代码少好理解。
public class Solution { public String largestNumber(int[] nums) { ArrayList<Number> list = new ArrayList<Number>(); for(int i : nums) { list.add(new Number(i+"")); } Collections.sort(list); StringBuilder sb = new StringBuilder(); for(int i=list.size()-1; i>=0; i--) { sb.append(list.get(i).val); } java.math.BigInteger b = new java.math.BigInteger(sb.toString()); return b.toString(); } } class Number implements Comparable<Number> { String val; public Number(String val) { this.val = val; } public int compareTo(Number n) { java.math.BigInteger a = new java.math.BigInteger(this.val + n.val); java.math.BigInteger b = new java.math.BigInteger(n.val + this.val); return a.compareTo(b); } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。