Suggest to Add An Test Case


  • 0
    A

    My C++ code has been accepted, but it is wrong since (nums.size()+1) * nums.size() will overflow when nums.size() is more than $\sqrt{2^32-1}$. So I suggest to add a test case that n is 2^16. The output of the following code is -2147418112. My compiler is GCC.

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int sum = 0;
            for(int i = 0; i < nums.size(); ++i){
                sum += nums[i];
            }
            return (nums.size()+1) * nums.size() / 2 - sum;
        }
    };
    int main()
    {
        Solution so;
        vector<int> c;
        for(int i = 0; i < 65536; ++i){
            c.push_back(i);
        }
        cout<<so.missingNumber(c)<<endl;
    }

  • 0

    Your solution would solve that test case correctly. Try it.


  • 0
    A

    No, I tried, and the output of code is -2147418112. The test data is shown in my code.


  • 0

    You tried wrong. A test on your PC is irrelevant, as the OJ doesn't use your PC to judge everybody. Submit the following to the OJ (I just added the first two lines) and you'll see your code produces the correct answer 65536:

    int missingNumber(vector<int>& nums) {
        nums.resize(65536);
        iota(begin(nums), end(nums), 0);
        int sum = 0;
        for(int i = 0; i < nums.size(); ++i){
            sum += nums[i];
        }
        return (nums.size()+1) * nums.size() / 2 - sum;
    }
    

  • 0
    A

    Yes, you are right. It seems that the OJ's compiier can deal with the problem


  • 0

    The reason btw is that nums.size() is a 64-bit value on the OJ, which you can see like this:

    int missingNumber(vector<int>& nums) {
        cout << sizeof(nums.size()) << endl;
    }

Log in to reply
 

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