My C++ solution, 4ms


  • 0
    2
    class Solution {
    public:
    static bool _Comp(int n1, int n2)
    {
    	if(n1 == n2)
    		return 0;
    	int s1 = 10;
    	while(s1 <= n1)
    		s1 *= 10;
    	int s2 = 10;
    	while(s2 <= n2)
    		s2 *= 10;
    	if(s1 == s2)
    		return n1>n2;
    	return (n2*s1+n1)<(n1*s2+n2);
    }
    
    string largestNumber(vector<int>& nums) 
    {
    	string out = "";
    	sort(nums.begin(), nums.end(), _Comp);
    	for(int i = 0; i < nums.size(); ++i)
    	{
    		string tmp = "";
    		for(int j = nums[i]; j; j/=10)
    			tmp = char(j%10+'0')+tmp;
    		if(tmp.size())
    			out += tmp;
    		else if(out != "0")
    			out += "0";
    	}
    	if(!out.size())
    		out = "0";
    	return out;
    }
    };

  • 0
    Z

    I considered using the comparing function same with yours, but what if (n2s1+n1) or (n1s2+n2) exceeds the limits of int? For example, take n2 or n1 be INT_MAX.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.