-
Notifications
You must be signed in to change notification settings - Fork 3
/
Plus One
27 lines (24 loc) · 834 Bytes
/
Plus One
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
int carry = 1; // Initialize the carry to 1
*returnSize = digitsSize;
// Traverse the digits array from right to left
for (int i = digitsSize - 1; i >= 0; i--) {
int sum = digits[i] + carry;
digits[i] = sum % 10; // Update the current digit
carry = sum / 10; // Update the carry
}
// If there's still a carry left, we need to add an additional digit
if (carry > 0) {
(*returnSize)++;
int* result = (int*)malloc(*returnSize * sizeof(int));
result[0] = carry;
for (int i = 1; i < *returnSize; i++) {
result[i] = digits[i - 1];
}
return result;
}
return digits;
}