[leetcode] problem 2 – add two numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

Code

1
2
3
4
5
public class  {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
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
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode current1 = l1;
ListNode current2 = l2;
ListNode current = head;
int carry = 0;

while (current1 != null || current2 != null) {
int val1 = current1 == null ? 0 : current1.val;
int val2 = current2 == null ? 0 : current2.val;
int sum = val1 + val2 + carry;

current.next = new ListNode(sum % 10);
carry = sum / 10;

current = current.next;

if (current1 != null)
current1 = current1.next;

if (current2 != null)
current2 = current2.next;
}

if (carry > 0)
current.next = new ListNode(carry);

return head.next;
}