- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path238.c
49 lines (38 loc) · 1.14 KB
/
238.c
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<stdio.h>
#include<stdlib.h>
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int*productExceptSelf(int*nums, intnumsSize, int*returnSize) {
if (nums==NULL||numsSize==0) returnNULL;
int*output= (int*)malloc(numsSize*sizeof(int));
*returnSize=numsSize;
inti;
for (i=0; i<numsSize; i++) { /* initialize all outputs to 1 */
output[i] =1;
}
intprodLeft=1; /* product from left */
for (i=1; i<numsSize; i++) {
prodLeft *= nums[i-1];
output[i] *= prodLeft;
}
intprodRight=1; /* product from right */
for (i=numsSize-2; i >= 0; i--){
prodRight *= nums[i+1];
output[i] *= prodRight;
}
returnoutput;
}
intmain() {
intnums[] = { 1, 2, 3, 4 };
intreturnSize=0;
int*output=productExceptSelf(nums, sizeof(nums)/sizeof(nums[0]), &returnSize);
inti;
for (i=0; i<returnSize; i++) {
printf("%d ", output[i]);
}
printf("\n");
free(output);
return0;
}