您的位置:首页 > 其它

*Largest Number

2015-10-09 04:12 232 查看
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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

class NumbersComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return (s2 + s1).compareTo(s1 + s2);
}
}

public class Solution {

public String largestNumber(int[] nums) {
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strs[i] = Integer.toString(nums[i]);
}
Arrays.sort(strs, new NumbersComparator());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs.length; i++) {
sb.append(strs[i]);
}
String result = sb.toString();
int index = 0;
while (index < result.length() && result.charAt(index) == '0') {
index++;
}
if (index == result.length()) {
return "0";
}
return result.substring(index,result.length());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: