题目
题解
题解1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode newHead = new ListNode(-1);
ListNode p = newHead;
ListNode p1 = l1;
ListNode p2 = l2;
int sum = 0, add = 0;
while (p1 != null && p2 != null) {
sum = (p1.val + p2.val) % 10;
ListNode next = new ListNode(sum + add);
add = (p1.val + p2.val) / 10;
p.next = next;
p = p.next;
p1 = p1.next;
p2 = p2.next;
}
if (p1 != null) {
ListNode next = new ListNode(p1.val + add);
p.next = next;
p = p.next;
p1 = p1.next;
}
if (p2 != null) {
ListNode next = new ListNode(p2.val + add);
p.next = next;
p = p.next;
p2 = p2.next;
}
return newHead.next;
}
}
错误
题解2
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode newHead = new ListNode(-1);
ListNode p = newHead;
ListNode p1 = l1;
ListNode p2 = l2;
int sum = 0, add = 0;
while (p1 != null && p2 != null) {
sum = (p1.val + p2.val + add) % 10;
ListNode next = new ListNode(sum);
add = (p1.val + p2.val + add) / 10;
p.next = next;
p = p.next;
p1 = p1.next;
p2 = p2.next;
}
while (p1 != null) {
sum = (p1.val + add) % 10;
ListNode next = new ListNode(sum);
add = (p1.val + add) / 10;
p.next = next;
p = p.next;
p1 = p1.next;
}
while (p2 != null) {
sum = (p2.val + add) % 10;
ListNode next = new ListNode(sum);
add = (p2.val + add) / 10;
p.next = next;
p = p.next;
p2 = p2.next;
}
// add
if (add != 0) {
ListNode next = new ListNode(add);
p.next = next;
p = p.next;
}
return newHead.next;
}
}