It's my C++ solution. Please feel free to comment.


  • 0
    B
     string largestNumber(vector<int> &num) {
       string result;
    	vector<int>::iterator i = num.begin();
    	vector<int>::iterator j;
    	for (; i != num.end(); i++)
    	{
    		int key = *i;
    		j = i+1;	
    		for (; j != num.end();j++)
    		{
    			if (compare(*j, *i))
    			{
    				int temp = *j;
    				*j = *i;
    				*i = temp;
    			}
    			
    		}
    	}
    	i = num.begin();
    	for (; i != num.end();i++)
    	{
    		stringstream ss;
    		ss << *i;
    		result.append(ss.str());
    		
    	}
    	if ( '0'== result[0])
    		return "0";
    	else 
    		return result;
    }
    bool compare(int a, int b)
    {
    	int tempa = a;
    	int tempaa = a;
    	int ia = 1;
    	int tempb = b;
    	int tempbb = b;
    	int ib=1;
    	while ((tempaa % 10 - tempaa) != 0)
    	{
    		tempaa = tempaa / 10;
    		ia++;
    	}
    	while ((tempbb % 10 - tempbb) != 0)
    	{
    		tempbb = tempbb / 10;
    		ib++;
    	}
    	if (ia >= ib)
    	{
    		tempb = tempb*pow(10, (ia - ib));
    		if (tempb >= tempa)
    			return false;
    		else if ((tempa - tempb) >= pow(10, (ia - ib)))
    			return true;
    		else
    			return compare((tempa - tempb), b);
    	}
    	else
    	{
    		tempa = tempa*pow(10, (ib - ia));
    		if (tempa >= tempb)
    			return true;
    		else if ((tempb - tempa) >= pow(10, (ib - ia)))
    			return false;
    		else
    			return compare(a, (tempb - tempa));
    	}
    }

Log in to reply
 

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