A simple C++ implementation


  • 2
    S
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
    		std::stable_sort(nums.begin(), nums.end(), compareGreater);
    		if (!nums.empty() && nums[0]==0)
    		{
    			return "0";
    		}
    		string val;
    		for (auto v : nums)
    		{
    			val += std::to_string(v);
    		}
    		return val;
    	}
    
    	static unsigned int numDigits(int num)
    	{
    		unsigned int count = 0;
    		do
    		{
    			count++;
    			num /= 10;
    		} while (num);
    		return count;
    	}
    
    	static bool  compareGreater(int lhs, int rhs)
    	{
    		unsigned int left_n = numDigits(lhs);
    		unsigned int right_n = numDigits(rhs);
    
    		unsigned int L = lhs*pow(10, right_n) + rhs;
    		unsigned int R = rhs*pow(10, left_n) + lhs;
    		return L > R;
    	}
    };

  • 0
    T
    This post is deleted!

  • 0
    C

    simple and impressive answer


Log in to reply
 

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