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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Output: 7 -> 0 -> 8
Sol 1: Recursive call the function.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) return null;
int num1 = (l1 == null)? 0 : l1.val;
int num2 = (l2 == null)? 0 : l2.val;
int sum = num1 + num2;
ListNode root = new ListNode(sum % 10);
int carry = sum / 10;
if (l1.next != null) {
l1.next.val += carry;
} else if (l2.next != null) {
l2.next.val += carry;
} else {
ListNode node = root;
while (carry > 0) {
node.next = new ListNode(carry % 10);
carry = carry / 10;
node = node.next;
}
return root;
}
ListNode node1 = (l1 == null)? new ListNode(0) : l1.next;
ListNode node2 = (l2 == null)? new ListNode(0) : l2.next;
root.next = addTwoNumbers(node1, node2);
return root;
}
Sol2: Use while loop to add numbers iteratively.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode root = new ListNode(0);
ListNode node = root;
ListNode p = l1;
ListNode q = l2;
int carry = 0;
while (p != null || q != null) {
int p_num = (p == null)? 0 : p.val;
int q_num = (q == null)? 0 : q.val;
int sum = p_num + q_num + carry;
carry = sum / 10;
sum = sum % 10;
if (p != null) p = p.next;
if (q != null) q = q.next;
node.next = new ListNode(sum);
node = node.next;
}
while (carry > 0) {
node.next = new ListNode(carry % 10);
node = node.next;
carry = carry / 10;
}
return root.next;
}
Remark: Iterative way is much more faster than recursive one in runtime. But the complexity is the same. Recursive way makes more readable / clean code.
留言
張貼留言