File tree 1 file changed +33
-1
lines changed
src/_Problems_/product-of-elements
1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -21,9 +21,41 @@ function findProduct(arr) {
21
21
let right = 1 ;
22
22
23
23
// multiply all the numbers to the right side
24
- for ( let i = arr . length - 1 ; i > 0 ; i -= 1 ) {
24
+ for ( let i = arr . length - 1 ; i >= 0 ; i -= 1 ) {
25
25
result [ i ] *= right ;
26
26
right *= arr [ i ] ;
27
27
}
28
28
return result ;
29
29
}
30
+
31
+ function findProduct2 ( arr ) {
32
+ let countZeros = 0 ;
33
+ let positionOfZero = - 1 ;
34
+ let productOffAllExpectZero = 1 ;
35
+ let result = [ ] ;
36
+ for ( let i = 0 ; i < arr . length ; i += 1 ) {
37
+ if ( arr [ i ] === 0 ) {
38
+ countZeros += 1 ;
39
+ positionOfZero = i ;
40
+ } else {
41
+ productOffAllExpectZero *= arr [ i ] ;
42
+ }
43
+ }
44
+
45
+ if ( countZeros === 0 ) {
46
+ for ( let i = 0 ; i < arr . length ; i += 1 ) {
47
+ result [ i ] = productOffAllExpectZero / arr [ i ] ;
48
+ }
49
+ } else if ( countZeros === 1 ) {
50
+ result = Array ( arr . length ) . fill ( 0 ) ;
51
+ result [ positionOfZero ] = productOffAllExpectZero ;
52
+ } else if ( countZeros >= 2 ) {
53
+ result = Array ( arr . length ) . fill ( 0 ) ;
54
+ }
55
+ return result ;
56
+ }
57
+
58
+ module . exports = {
59
+ findProduct,
60
+ findProduct2,
61
+ } ;
You can’t perform that action at this time.
0 commit comments