Skip to content

Commit 9538418

Browse files
committed
add solution for Leetcode 238
1 parent e5dad3f commit 9538418

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

leetcode/src/238.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
int *productExceptSelf(int *nums, int n, int *returnSize) {
2+
int totalProd = 1, prefProd = 1, count0 = 0;
3+
4+
// Count zeros and calculate product of non-zero elements
5+
for (int i = 0; i < n; i++) {
6+
if (nums[i] == 0) {
7+
count0++;
8+
} else {
9+
totalProd *= nums[i];
10+
}
11+
}
12+
13+
int *res = (int *)malloc(n * sizeof(int));
14+
15+
for (int i = 0; i < n; i++) {
16+
if (nums[i] != 0) {
17+
prefProd *= nums[i];
18+
}
19+
if (count0 > 1) {
20+
res[i] = 0;
21+
} else {
22+
if (count0 == 0) {
23+
res[i] = (totalProd / prefProd) * (prefProd / nums[i]);
24+
} else {
25+
if (nums[i] == 0) {
26+
res[i] = (totalProd / prefProd) * (prefProd);
27+
} else {
28+
res[i] = 0;
29+
}
30+
}
31+
}
32+
}
33+
*returnSize = n;
34+
return res;
35+
}

0 commit comments

Comments
 (0)