您的位置:首页 > 其它

[leetcode] Largest Number

2015-06-20 15:09 302 查看
From : https://leetcode.com/problems/largest-number/
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.
class Solution {
public:
static int comp(int a, int b) {
string sa = to_string(a);
string sb = to_string(b);
return sa+sb > sb+sa;
}
string largestNumber(vector<int>& nums) {
if(nums.size() == 0) return "";
sort(nums.begin(), nums.end(), comp);
string ans = "";
for(int i=0, l=nums.size(); i<l; i++) {
ans += to_string(nums[i]);
}
if(ans[0] == '0') return "0";
return ans;
}
};


public class Solution {
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return "";
}
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; ++i) {
strs[i] = String.valueOf(nums[i]);
}

Arrays.sort(strs, new Comparator<String>() {
public int compare(String a, String b) {
return (b + a).compareTo(a + b);
}
});

if(strs[0].equals("0")) {
return "0";
}
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s);
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: