-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
43 lines (43 loc) · 1.07 KB
/
AddTwoNumbers.java
File metadata and controls
43 lines (43 loc) · 1.07 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, cur = null;
int carry = 0;
while (l1 != null || l2 != null) {
int a = 0, b = 0;
if (l1 != null) {
a = l1.val;
l1 = l1.next;
}
if (l2 != null) {
b = l2.val;
l2 = l2.next;
}
int sum = a + b + carry;
ListNode l3 = new ListNode(sum % 10);
carry = sum / 10;
if (head == null) {
head = l3;
cur = head;
}
else {
cur.next = l3;
cur = cur.next;
}
}
if (carry != 0) {
cur.next = new ListNode(carry);
}
return head;
}
}