Thursday, February 5, 2015

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.
class Solution {
public:
    string largestNumber(vector<int> &num) {
        vector<string> str;
        for (int i=0;i<num.size();i++)
            str.push_back(to_string(num[i]));
        sort(str.begin(),str.end(),compare);
        string res;
        int i=0;
        while(i<str.size()-1 && str[i]=="0")
            i++;
        for (;i<str.size();i++)
            res += str[i];
        return res;
    }
    static bool compare(string s1,string s2)
    {
        return (s1+s2)>(s2+s1);
    }
};

No comments:

Post a Comment