C++ solution using sort compare function


  • 0
    X
    bool compFunction (int a, int b) {
        return (to_string(a) + to_string(b)) > (to_string(b) + to_string(a));
    }
    
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            if (nums.size() == 0) return "";
            sort(nums.begin(), nums.end(), compFunction);
            string res = "";
            for (auto num : nums)
                res += to_string(num);
            //remove redundant zeroes
            if (res.length() != 0) {
                int i = 0;
                while (res[i] == '0' && i < res.length() - 1) i++;
                res = res.substr(i);
            }
            return res;
        }
    };

Log in to reply
 

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