class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode temp = new ListNode(0);
ListNode result = temp;
while (l1 != null || l2 != null) {
int sum = (l1 != null? l1.val: 0) + (l2 != null? l2.val: 0) + carry;
carry = sum / 10; temp.next = new ListNode(sum % 10);
l1 = l1 != null? l1.next: l1;
l2 = l2 != null? l2.next: l2;
temp = temp.next;
}
if (carry > 0) {
temp.next = new ListNode(carry);
}
return result.next;
}
}
网友评论