LeetCode 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 Cmp {
public:
    bool operator() (const string& a, const string& b) {
        return cmp(a + b, b + a, a.size() + b.size());
    }
    
    bool cmp(const string a, const string b, int len) {
        int pos = 0;
        while (pos < len) {
            if (a[pos] != b[pos]) {
                return a[pos] < b[pos];
            }
            pos++;
        }
        return false;        
    }
};
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> strnums;
        for (int num : nums) {
            strnums.push_back(num2str(num));
        }
        
        sort(strnums.begin(), strnums.end(), Cmp());
        
        string res;
        int len = strnums.size();
        for (int i=len - 1; i>=0; i--) {
            if (res.size() == 0 && strnums[i][0] == '0') {
                continue;
            }
            res = res + strnums[i];
        }
        if (res.size() == 0) {
            res = "0";
        }
        return res;
    }
    
    string num2str(int num) {
        char buf[20] = {0};
        sprintf(buf, "%d", num);
        return string(buf);
    }
};

你可能感兴趣的:(LeetCode)