[LeetCode] 179. Largest Number

Posted 医生工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 179. 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.

利用sort函数,自己写一个比较函数compare,比较两个数字连接起来哪个大进行排序。

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        string restr = "";
        sort(nums.begin(), nums.end(), compare);
        for (int i = 0; i < nums.size(); ++i){
            restr += to_string(nums[i]);
        }
        if (restr[0] == 0){
            return "0";
        }
        return restr;
    }
    
    static bool compare(int a, int b){
        string stra = to_string(a);
        string strb = to_string(b);
        
        return stra + strb > strb + stra;
    }
};

 

以上是关于[LeetCode] 179. Largest Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(179) Largest Number

leetcode 179. Largest Number

Leetcode179. Largest Number

[LeetCode] 179. Largest Number

leetcode 179 Largest Number

[leetcode sort]179. Largest Number