A Readable C++ Solution, 8 ms Time Consumption


  • 2
    B

    The comparing function is the keypoint, and 'sprintf' is a good choice for Digit-To-String manipulation.

    class Solution {
    public:
        struct node{
            int n;
            int width;
            node(int _n, int _width):n(_n), width(_width){}
            friend bool operator<(const node &A, const node &B){
                return ((long long)A.n * B.width + B.n) > ((long long)B.n * A.width + A.n);
            }
        };
        string largestNumber(vector<int> &num) {
            vector<node> buf;
            for(int i = 0; i < num.size(); i ++){
                int k = 10;
                while(k <= num[i])k *= 10;
                buf.push_back(node(num[i],k));
            }
            sort(buf.begin(),buf.end());
            string ans;
            char numToStr[50];
            for(vector<node>::iterator it = buf.begin(); it != buf.end(); it ++){
                sprintf(numToStr,"%d",it->n);
                ans += numToStr;
            }
            if(ans.length() < 1 || ans[0] == '0')ans = "0";
            return ans;
        }
    };

Log in to reply
 

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