LX

潜下心好好学习

Leetcode160: 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 bool compare(string& s1, string& s2)
    {
        return (s1+s2)>(s2+s1);
    }
    string largestNumber(vector<int>& nums) {
        vector<string> num(nums.size());
        for(int i = 0; i < nums.size(); i++)
        {
            num[i] = to_string(nums[i]);
        }
        sort(num.begin(), num.end(), compare);
        string res;
        bool flag = false;
        for(int i = 0; i < num.size(); i++)
        {
            if(num[i] != "0"){
                res += num[i];
                flag = true;
            }
            else if(flag)
            {
                res += num[i];
            }
        }
        if(!flag) res.push_back('0');
        return res;
    }
};


阅读更多
文章标签: leetcode algorithm
个人分类: c++ leetcode
上一篇Leetcode159: Fraction to Recurring Decimal
下一篇Leetcode161: Repeated DNA Sequences
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭