Skip to content

Commit d7dd40c

Browse files
committed
Problem02 using ArrayList
1 parent 8575e8c commit d7dd40c

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

java8/src/main/java/com/shekhargulati/leetcode/Problem01.java renamed to java8/src/main/java/com/shekhargulati/leetcode/algorithms/Problem01.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.shekhargulati.leetcode;
1+
package com.shekhargulati.leetcode.algorithms;
22

33
import java.util.Arrays;
44
import java.util.HashMap;
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.shekhargulati.leetcode.algorithms;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/**
8+
* You are given two linked lists representing two non-negative numbers.
9+
* The digits are stored in reverse order and each of their nodes contain a single digit.
10+
* Add the two numbers and return it as a linked list.
11+
* <p>
12+
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
13+
* Output: 7 -> 0 -> 8
14+
*/
15+
public class Problem02 {
16+
17+
public static void main(String[] args) {
18+
/*
19+
1. Iterate over two lists together
20+
2. Add the two numbers at ith position
21+
3. If numbers add upto greater than equal to 10 then store the remainder at current position and store 1 as next
22+
4. When you are adding up next number add one
23+
*/
24+
25+
long start = System.currentTimeMillis();
26+
List<Integer> first = Arrays.asList(2, 4, 3);
27+
List<Integer> second = Arrays.asList(5, 6, 4);
28+
29+
List<Integer> result = new ArrayList<>();
30+
31+
int rem = 0;
32+
for (int i = 0; i < first.size(); i++) {
33+
int a = first.get(i);
34+
int b = second.get(i);
35+
int sum = a + b;
36+
if (a + b >= 10) {
37+
result.add(rem + sum % 10);
38+
rem = 1;
39+
} else {
40+
result.add(rem + sum);
41+
rem = 0;
42+
}
43+
}
44+
45+
System.out.println(result);
46+
long end = System.currentTimeMillis();
47+
System.out.println(String.format("Total time taken %d millis", (end - start)));
48+
49+
}
50+
51+
private class ListNode {
52+
int val;
53+
ListNode next;
54+
55+
public ListNode(int val) {
56+
this.val = val;
57+
}
58+
}
59+
60+
}

java8/src/test/java/com/shekhargulati/leetcode/Problem01Test.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.shekhargulati.leetcode;
22

3+
import com.shekhargulati.leetcode.algorithms.Problem01;
34
import org.junit.Test;
45

56
import java.util.Arrays;

0 commit comments

Comments
 (0)