Skip to content

Commit b241cc3

Browse files
Time: 0 ms (100.00%) | Memory: 9.8 MB (74.63%) - LeetSync
1 parent cd7f242 commit b241cc3

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

‎66-plus-one/plus-one.c‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <stdlib.h>
2+
#include <string.h>
3+
4+
int* plusOne(int* digits, int digitsSize, int* returnSize) {
5+
// 1. Traverse from right to left to handle addition and carry propagation
6+
for (int i = digitsSize - 1; i >= 0; i--) {
7+
if (digits[i] < 9) {
8+
digits[i]++;
9+
10+
// Allocate a clean copy of size digitsSize to return
11+
int* result = (int*)malloc(digitsSize * sizeof(int));
12+
memcpy(result, digits, digitsSize * sizeof(int));
13+
*returnSize = digitsSize;
14+
return result;
15+
}
16+
// Digit was 9: becomes 0 and carry continues to the next iteration
17+
digits[i] = 0;
18+
}
19+
20+
// 2. Overflow case: all digits were 9 (e.g., [9, 9] -> [1, 0, 0])
21+
int newSize = digitsSize + 1;
22+
// calloc automatically initializes all elements to 0
23+
int* result = (int*)calloc(newSize, sizeof(int));
24+
result[0] = 1;
25+
*returnSize = newSize;
26+
27+
return result;
28+
}

0 commit comments

Comments
 (0)