-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2_Add_Two_Numbers.java
More file actions
56 lines (45 loc) · 1.39 KB
/
LC2_Add_Two_Numbers.java
File metadata and controls
56 lines (45 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package practise.leetCode;
public class LC2_Add_Two_Numbers {
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
System.out.println("list 1");
printList(l1);
System.out.println("list 2");
printList(l2);
System.out.println("output : ");
printList(addTwoNumbers(l1, l2));
}
private static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode();
ListNode temp = res;
int total, carry = 0;
while (l1 != null || l2 != null || carry != 0) {
total = carry;
if (l1 != null) {
total += l1.val;
l1 = l1.next;
}
if (l2 != null) {
total += l2.val;
l2 = l2.next;
}
int num = total % 10;
carry = total / 10;
temp.next = new ListNode(num);
temp = temp.next;
}
return res.next;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
}