File tree Expand file tree Collapse file tree
main/java/com/devstromo/day814
test/java/com/devstromo/day814 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 55public class Problem {
66
77 public long sumTwoLinkedList (LinkedList <Integer > list1 , LinkedList <Integer > list2 ) {
8- var first = 0L ;
9- var second = 0L ;
10- var pos = 0 ;
11- final var n = list1 .size ();
12- final var m = list2 .size ();
13-
14- for (pos = 0 ; pos < n ; pos ++) {
15- first += list1 .get (pos ) * pow (pos );
8+ if (list1 == null && list2 == null ) {
9+ return 0 ;
10+ }
11+ if (list2 == null ) {
12+ return listNumberRepresentation (list1 , list1 .size ());
1613 }
17- for ( pos = 0 ; pos < m ; pos ++ ) {
18- second += list2 .get ( pos ) * pow ( pos );
14+ if ( list1 == null ) {
15+ return listNumberRepresentation ( list2 , list2 .size () );
1916 }
17+ var first = listNumberRepresentation (list1 , list1 .size ());
18+ var second = listNumberRepresentation (list2 , list2 .size ());
2019 return first + second ;
2120 }
2221
@@ -32,4 +31,12 @@ private long pow(long exp) {
3231 }
3332 return result ;
3433 }
34+
35+ private long listNumberRepresentation (LinkedList <Integer > list , int size ) {
36+ var result = 0L ;
37+ for (int pos = 0 ; pos < size ; pos ++) {
38+ result += list .get (pos ) * pow (pos );
39+ }
40+ return result ;
41+ }
3542}
Original file line number Diff line number Diff line change @@ -20,4 +20,20 @@ public void testSumTwoLinkedList() {
2020 assertEquals (124 , problem .sumTwoLinkedList (list1 , list2 ));
2121 }
2222
23+ @ Test
24+ public void testSumTwoLinkedListWithList2Null () {
25+ final var list1 = new LinkedList <Integer >();
26+ list1 .add (9 );
27+ list1 .add (9 );
28+ assertEquals (99 , problem .sumTwoLinkedList (list1 , null ));
29+ }
30+
31+ @ Test
32+ public void testSumTwoLinkedListWithList1Null () {
33+ final var list2 = new LinkedList <Integer >();
34+ list2 .add (5 );
35+ list2 .add (2 );
36+ assertEquals (25 , problem .sumTwoLinkedList (null , list2 ));
37+ }
38+
2339}
You can’t perform that action at this time.
0 commit comments