Skip to content

Commit 188c049

Browse files
authored
Merge pull request #2962 from mdmzfzl/main
Create: 0989-add-to-array-form-of-integer.c
2 parents 8b48dd5 + 19641eb commit 188c049

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

c/0989-add-to-array-form-of-integer.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
int* addToArrayForm(int* A, int ASize, int K, int* returnSize) {
2+
// Calculate the maximum size of the result array
3+
int maxSize = (ASize > 6) ? ASize + 2 : 8; // Maximum 6 digits in K, plus 2 for potential carry.
4+
5+
// Create the result array
6+
int* result = (int*)malloc(maxSize * sizeof(int));
7+
8+
// Initialize variables
9+
int carry = 0;
10+
int i = ASize - 1;
11+
int j = 0;
12+
13+
// Perform the addition
14+
while (i >= 0 || K > 0 || carry > 0) {
15+
int sum = carry;
16+
if (i >= 0) {
17+
sum += A[i];
18+
i--;
19+
}
20+
if (K > 0) {
21+
sum += K % 10;
22+
K /= 10;
23+
}
24+
25+
result[j] = sum % 10;
26+
carry = sum / 10;
27+
j++;
28+
}
29+
30+
// Reverse the result array
31+
int left = 0;
32+
int right = j - 1;
33+
while (left < right) {
34+
int temp = result[left];
35+
result[left] = result[right];
36+
result[right] = temp;
37+
left++;
38+
right--;
39+
}
40+
41+
*returnSize = j;
42+
return result;
43+
}

0 commit comments

Comments
 (0)