Online Judge Solutions

Tuesday, January 27, 2015

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.
bool myCompare (string i, string j) 
{ 
    return (i+j) > (j+i); 
}

class Solution {
public:
    string largestNumber(vector<int> &num) {
        vector<string> tmp;
        bool allZero = true;
        for(int i : num) {
           allZero = allZero && i == 0;
           tmp.push_back(to_string(i));
        }
        
        if (allZero) return "0";
        
        sort(tmp.begin(), tmp.end(), myCompare);
        string output = "";
        
        for(string s : tmp)
           output+=s;
           
        return output;
    }
};

No comments:

Post a Comment