LeetCode——Largest Number

时间:2024-12-14 23:05:45

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