C++, why it is WA?


  • 0
    A
    class Solution {
    private:
    static bool cmp(int a, int b)
    {
        if (a == 0) return false;
        if (b == 0) return true;
        stringstream  ssa, ssb;
        ssa << a;
        ssb << b;
        string stra = ssa.str()+ssb.str(), strb = ssb.str()+ssa.str();
        if (stra.compare(strb) == 1) return true; // >
        else return false;
    }
    public:
    string largestNumber(vector<int>& nums)
    {
        sort(nums.begin(), nums.end(), cmp);
        if (nums[0] == 0) return string("0");
        string ret;
        stringstream ss;
        for (int i = 0; i < nums.size(); i++) {
    		ss << nums[i];
    		ret += ss.str();
    		ss.str(""); // clear
        }
        return ret;
    }
    };

  • 0
    A

    the sample [123, 321], the local test is right, output is 321123, but submit in leetcode, output is 123321, why???!!!


  • 0

    The problem is stra.compare(strb) == 1, because compare returns a positive/negative/zero value. Can be a positive value other than 1.

    Btw, return stra > strb; would be a lot simpler.


Log in to reply
 

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