/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0);
ListNode head = res;
int carry = 0;
while (l1!=null & l2!=null) {
head.next = new ListNode((l1.val+l2.val+carry)%10);
carry = (l1.val+l2.val+carry)/10;
l1 = l1.next;
l2 = l2.next;
head = head.next;
}
while (l1!=null && l2==null) {
head.next = new ListNode((l1.val+carry)%10);
carry = (l1.val+carry)/10;
l1 = l1.next;
head = head.next;
}
while (l1==null && l2!=null) {
head.next = new ListNode((l2.val+carry)%10);
carry = (l2.val+carry)/10;
l2 = l2.next;
head = head.next;
}
if (carry==1) head.next = new ListNode(1);
return res.next;
}
}
没有评论:
发表评论