-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode00002.java
101 lines (87 loc) · 2.51 KB
/
Leetcode00002.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* 2. Add Two Numbers
*
* @link https://leetcode.com/problems/add-two-numbers
* @author vutiendat3601
* @date 2024-06-06
*/
public class Leetcode00002 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Calculate the first nodes
final ListNode result = new ListNode((l1.val + l2.val) % 10);
int carry = l1.val + l2.val >= 10 ? 1 : 0;
ListNode head = result;
l1 = l1.next;
l2 = l2.next;
// While two lists not reach to after the end node
while (l1 != null && l2 != null) {
head.next = new ListNode((l1.val + l2.val + carry) % 10);
carry = (l1.val + l2.val + carry) >= 10 ? 1 : 0;
head = head.next;
l1 = l1.next;
l2 = l2.next;
}
// While the first list not reach to after the end node
while (l1 != null) {
head.next = new ListNode((l1.val + carry) % 10);
carry = (l1.val + carry) >= 10 ? 1 : 0;
head = head.next;
l1 = l1.next;
}
// While the second list not reach to after the end node
while (l2 != null) {
head.next = new ListNode((l2.val + carry) % 10);
carry = (l2.val + carry) >= 10 ? 1 : 0;
head = head.next;
l2 = l2.next;
}
if (carry > 0) {
head.next = new ListNode(1);
}
return result;
}
public static void main(String[] args) {
final ListNode l1 = ListNode.from(2, 4, 9);
final ListNode l2 = ListNode.from(5, 6, 4, 9);
final Leetcode00002 leetcode00002 = new Leetcode00002();
final ListNode result = leetcode00002.addTwoNumbers(l1, l2);
ListNode.print(result);
}
static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override
public String toString() {
return String.valueOf(val);
}
public static ListNode from(int... nums) {
final ListNode beforeHead = new ListNode();
if (nums != null && nums.length > 0) {
beforeHead.next = new ListNode(nums[0]);
ListNode head = beforeHead.next;
for (int i = 1; i < nums.length; i++) {
head.next = new ListNode(nums[i]);
head = head.next;
}
}
return beforeHead.next;
}
public static void print(ListNode head) {
if (head != null) {
while (head.next != null) {
System.out.print(head.val + "->");
head = head.next;
}
System.out.println(head.val);
}
}
}
}