C solution problem


  • 0
    S

    I am not sure what's going on with this solution. When I run the test case [9,9,9] or [9,9,9,9] they return the right result [1, 0, 0, 0] or [1, 0, 0, 0, 0], but when I submit the solution I get incorrect value for [9,9,9] which is [1,0,4,0] and submit fails. How is it possible that I get [1,0,4,0] on submit, but not on test run? Could anyone please point out the error in this code why the submission fails?

    Thanks in advance.

    int*plusOne(int* digits, int digitsSize, int* returnSize) {
    int i;
    for (i = digitsSize-1; i >= 0; i--) {
        digits[i] += 1;
        if (digits[i] <= 9) {
            *returnSize = digitsSize;
            return digits;
        }
        // digits[i] > 9, dec overflow
        digits[i] = 0;
    }
    int * nums = (int*) malloc(sizeof(int) * digitsSize+1);
    nums[0] = 1;
    memcpy(nums + 1, digits, sizeof(int));
    *returnSize = digitsSize + 1;
    return nums;
    

    }


  • 0
    S

    Found the bug after looking at it the next day. Silly. Memcopy should be instead:

      memcpy(nums + 1, digits, sizeof(int)*digitsSize);

Log in to reply
 

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