LeetCode 2. 两数相加
原题链接
中等
作者:
rainclaire
,
2020-08-19 05:45:13
,
所有人可见
,
阅读 2
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead;
int carry = 0;
while (p != null || q!= null) {
int x = p != null ? p.val : 0;
int y = q != null ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
//take care of last sum carry to final result
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}