C++ soution running at 7ms


  • 1
    A
    class Solution {
    public:
        string largestNumber(vector<int> &num) {
            sort(begin(num), end(num), [](int a, int b) {
                int i= 10, j= 10;
                while(a/i) {
                    i*=10;
                }
                while(b/j) {
                    j*=10;
                }
                int aa= a*j+b;
                int bb= b*i+a;
                return aa>bb;
            });
            stringstream sstrm;
            bool z= false;
            for(auto i: num) {
                if(z || i!=0) {
                    sstrm<<i;
                    z= true;
                }
            }
            if(!z) {
                sstrm<<0;
            }
            return sstrm.str();
        }
    };

  • 1
    J

    your code will overflow integer.
    int aa= a*j+b;
    a and j could be very large that aa can't hold it.
    { 999999998, 999999997, 999999999 }
    your code give "999999998999999997999999999".

    This is also an indication of test cases problem if your code really pass.


  • 1

    Thanks for the sharp eye and the test case, @jianhualiu2! I have just added your test case and the code should get Wrong Answer.


Log in to reply
 

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