image_2022-04-28_15-31-26.png
54.1 KB
#medium
#N2. Add Two Numbers
problem link
#solution
#N2. Add Two Numbers
problem link
#solution
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode temp = head;
int carry=0;
while(l1!=null || l2!=null){
temp.next=new ListNode();
temp=temp.next;
temp.val = (l1!=null?l1.val:0) + (l2!=null?l2.val:0)+carry;
carry=temp.val/10;
temp.val %= 10;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
}
if(carry>0)
temp.next = new ListNode(carry);
return head.next;
}
}