Add Two Numbers
description:
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.
思路1
遍历L1和L2,逐位相加,并用carry来记录进位,carry等于0或1,当L1遍历完时继续遍历L2,当L2遍历完时继续遍历L1,代码如下:
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
int carry = 0;
ListNode resNode = new ListNode(0);
ListNode currentNode = resNode;
while(l1 != null && l2 != null) {
ListNode nextNode = null;
if (l1.val + l2.val + carry > 9) {
nextNode = new ListNode(l1.val + l2.val + carry - 10);
carry = 1;
}else {
nextNode = new ListNode(l1.val + l2.val + carry);
carry = 0;
}
currentNode.next = nextNode;
currentNode = nextNode;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
if (l1.val + carry > 9) {
ListNode nextNode = new ListNode(l1.val + carry - 10);
currentNode.next = nextNode;
currentNode = nextNode;
l1 = l1.next;
carry = 1;
}else {
ListNode nextNode = new ListNode(l1.val + carry);
nextNode.next = l1.next;
currentNode.next = nextNode;
return resNode.next;
}
}
while (l2 != null) {
if (l2.val + carry > 9) {
ListNode nextNode = new ListNode(l2.val + carry - 10);
currentNode.next = nextNode;
currentNode = nextNode;
l2 = l2.next;
carry = 1;
}else {
ListNode nextNode = new ListNode(l2.val + carry);
nextNode.next = l2.next;
currentNode.next = nextNode;
return resNode.next;
}
}
if (carry == 1) {
ListNode nextNode = new ListNode(carry);
currentNode.next = nextNode;
}
return resNode.next;
}
错误提交1
Input: [1]
[9,9]
Output: [0,1]
Expected: [0,0,1]
原因:L1和L2都遍历完后,还需要判断carry是否为1,如果为1,还需要再创建一个节点。
if (carry == 1) {
ListNode nextNode = new ListNode(carry);
currentNode.next = nextNode;
}
错误提交2
Input: [9]
[1,9,9,9,9,9,8,9,9,9]
Output: [0,0,0,0,0,0,9]
Expected: [0,0,0,0,0,0,9,9,9,9]
原因:当遍历完L1时,L2不为null,继续遍历L2,直到8时不再产生进位,直接返回结果,还需要把当前节点指向L2剩余节点。
- 错误代码:
if (l1.val + carry > 9) {
ListNode nextNode = new ListNode(l1.val + carry - 10);
currentNode.next = nextNode;
currentNode = nextNode;
l1 = l1.next;
carry = 1;
}else {
ListNode nextNode = new ListNode(l1.val + carry);
currentNode.next = nextNode;
return resNode.next;
}
- 正确代码:
if (l1.val + carry > 9) {
ListNode nextNode = new ListNode(l1.val + carry - 10);
currentNode.next = nextNode;
currentNode = nextNode;
l1 = l1.next;
carry = 1;
}else {
ListNode nextNode = new ListNode(l1.val + carry);
nextNode.next = l1.next;
currentNode.next = nextNode;
return resNode.next;
}