Skip to content

Latest commit

 

History

History
95 lines (74 loc) · 2.25 KB

_66. Plus One.md

File metadata and controls

95 lines (74 loc) · 2.25 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 03, 2024

Last updated : July 01, 2024


Related Topics : Array, Math

Acceptance Rate : 46.34 %


Solutions

C

// Version that doesn't deal with the free() issue but uses some more memory in the process during shifting :v

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize) {
    int* output = (int*) malloc(sizeof(int) * digitsSize);

    bool carry = true;
    for (int i = digitsSize - 1; i >= 0; i--) {
        int temp = digits[i] + ((carry) ? 1 : 0);
        if (temp > 9) {
            carry = true;
            output[i] = (temp - 10);
        } else {
            carry = false;
            output[i] = temp;
        }
    }

    *returnSize = (carry) ? digitsSize + 1 : digitsSize;

    if (!carry) {
        return output;
    }

    int* output2 = (int*) malloc(sizeof(int) * (1 + digitsSize));
    output2[0] = 1;
    memcpy(output2 + 1, output, sizeof(int) * digitsSize); 
    free(output);
    return output2;

}
// Beats 100% but this notably might have free() issues with output if it has a carry on the last digit :l

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize) {
    int* output = (int*) malloc(sizeof(int) * (digitsSize + 1));

    bool carry = true;
    for (int i = digitsSize - 1; i >= 0; i--) {
        int temp = digits[i] + ((carry) ? 1 : 0);
        if (temp > 9) {
            carry = true;
            output[i + 1] = (temp - 10);
        } else {
            carry = false;
            output[i + 1] = temp;
        }
    }

    *returnSize = (carry) ? digitsSize + 1 : digitsSize;

    if (carry) {
        output[0] = 1;
        return output;
    } else {
        return output + 1;
    }
}