首页 > 代码库 > [leetcode]179 Largest Number

[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 is9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

代码:

bool myFun(string s1,string s2){  //C++
        if(s1.size() == s2.size())
            return s1>s2;
        
        int llen,slen;
        string longstr,shortstr;
        if(s1.size()>=s2.size()){
            llen = s1.size();
            slen = s2.size();
            longstr = s1;
            shortstr = s2;
        }
        else {
            llen = s2.size();
            slen = s1.size();
            longstr = s2;
            shortstr = s1;
        }
        
        for(int i=0; i<llen*slen; i++)
        {
            if(shortstr[i%slen]==longstr[i%llen])
                continue;
            else if(shortstr[i%slen] > longstr[i%llen])
            {
                if(s1.size()>=s2.size())
                    return false;
                return true;
            }
            else{
              if(s1.size() >= s2.size())
                    return true;
              return false;  
            } 
        }
        return true;
    }
class Solution {
public:
    string largestNumber(vector<int> &num) {
        if(num.size() == 0)
            return "";
        
        int i;
        for( i=0; i<num.size(); i++)
            if(num[i]!=0)
                break;
        if(i==num.size())
            return "0";
        
        stringstream ss;
        vector<string> numstr;
        string result ="";
        for(int i=0; i< num.size(); i++){
            ss << num[i];
            string temp = ss.str();
            ss.str("");
            numstr.push_back(temp);
        }
        sort(numstr.begin(),numstr.end(),myFun);
        for(int i=0; i<numstr.size(); i++)
            result += numstr[i];
            
        return result;
    }
};


[leetcode]179 Largest Number