File tree Expand file tree Collapse file tree 2 files changed +28
-10
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +28
-10
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
+ import java .util .ArrayList ;
4
+ import java .util .List ;
5
+
3
6
/**
4
7
* 1352. Product of the Last K Numbers
5
8
*
37
40
* */
38
41
public class _1352 {
39
42
public static class Solution1 {
43
+ /**credit: https://leetcode.com/problems/product-of-the-last-k-numbers/discuss/510260/JavaC%2B%2BPython-Prefix-Product*/
40
44
public static class ProductOfNumbers {
41
45
42
- public ProductOfNumbers () {
46
+ List < Integer > list ;
43
47
48
+ public ProductOfNumbers () {
49
+ add (0 );
44
50
}
45
51
46
52
public void add (int num ) {
47
-
53
+ if (num > 0 ) {
54
+ list .add (list .get (list .size () - 1 ) * num );
55
+ } else {
56
+ list = new ArrayList <>();
57
+ list .add (1 );
58
+ }
48
59
}
49
60
50
61
public int getProduct (int k ) {
51
- return -1 ;
62
+ int size = list .size ();
63
+ return k >= size ? 0 : (list .get (size - 1 ) / list .get (size - k - 1 ));
52
64
}
53
65
}
54
66
}
Original file line number Diff line number Diff line change 1
1
package com .fishercoder ;
2
2
3
3
import com .fishercoder .solutions ._1352 ;
4
- import org .junit .BeforeClass ;
5
4
import org .junit .Test ;
6
5
6
+ import static org .junit .Assert .assertEquals ;
7
+
7
8
public class _1352Test {
8
9
private static _1352 .Solution1 .ProductOfNumbers productOfNumbers ;
9
10
10
- @ BeforeClass
11
- public static void setup () {
12
- productOfNumbers = new _1352 .Solution1 .ProductOfNumbers ();
13
- }
14
-
15
11
@ Test
16
12
public void test1 () {
17
-
13
+ productOfNumbers = new _1352 .Solution1 .ProductOfNumbers ();
14
+ productOfNumbers .add (3 );
15
+ productOfNumbers .add (0 );
16
+ productOfNumbers .add (2 );
17
+ productOfNumbers .add (5 );
18
+ productOfNumbers .add (4 );
19
+ assertEquals (20 , productOfNumbers .getProduct (2 ));
20
+ assertEquals (40 , productOfNumbers .getProduct (3 ));
21
+ assertEquals (0 , productOfNumbers .getProduct (4 ));
22
+ productOfNumbers .add (8 );
23
+ assertEquals (32 , productOfNumbers .getProduct (2 ));
18
24
}
19
25
20
26
}
You can’t perform that action at this time.
0 commit comments