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

LeetCode——Largest Number

时间:2015-06-26 06:50:25      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }
}

 

LeetCode——Largest Number

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4601330.html

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