File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments