LeetCode - Largest Number (sort的cmp的写法)

来源:互联网 发布:大雄的生化危机 知乎 编辑:程序博客网 时间:2024/04/30 10:11

Largest Number

 Total Accepted: 23153 Total Submissions: 146500My Submissions

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:    string largestNumber(vector<int>& nums) {        vector<string> strs;        for(auto x : nums)            strs.push_back(to_string(x));        sort(strs.begin(), strs.end(), cmp);        string ans;        for(auto s : strs)            ans += s;        return ans[0] == '0' ? "0" : ans;    }private:    static bool cmp(string a, string b){        return a + b > b + a;    }    };


0 0