Skip to content

Commit 6489cc1

Browse files
committed
update 2.add_two_numbers.java
1 parent 0eaf04c commit 6489cc1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

2.add_two_numbers.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
13+
// init new ListNode
14+
ListNode dummyRoot = new ListNode(0);
15+
ListNode l3 = dummyRoot;
16+
// init a carry variable to 0
17+
int carry = 0;
18+
int sum;
19+
int x;
20+
int y;
21+
22+
// loop over the size of the biggest ListNode
23+
while (l1 != null || l2 != null) {
24+
x = (l1 != null) ? l1.val : 0;
25+
y = (l2 != null) ? l2.val : 0;
26+
// Add l1 and l2 + carry at given index,
27+
// storing the 10s place into carry var and the sum into new ListNode
28+
sum = x + y + carry;
29+
l3.next = new ListNode(sum % 10);
30+
// Traverse next node
31+
if (l1 != null) l1 = l1.next;
32+
if (l2 != null) l2 = l2.next;
33+
l3 = l3.next;
34+
35+
// store carry
36+
carry = sum / 10;
37+
}
38+
// Store carry into last node if > 0
39+
if (carry > 0) {
40+
l3.next = new ListNode(carry);
41+
}
42+
return dummyRoot.next;
43+
}
44+
}

0 commit comments

Comments
 (0)