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.
写一个方法,把数字连起来,比较字符串大小。之所以不再atoi比较数字大小是因为可能会溢出。最后还要考虑数组全是0的情况。
class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), compare);
string res = "";
for (auto it = nums.begin(); it != nums.end(); ++it) {
res += to_string(*it);
}
if (res[0] == '0')
res = "0";
return res;
}
static bool compare(int a, int b) {
string str_a = to_string(a), str_b = to_string(b);
string tmp1 = str_a + str_b, tmp2 = str_b + str_a;
return tmp1 > tmp2;
}
};