class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(0);
ListNode yummy = ans;
int flag = 0;
int node = 0 ;
while(l1 !=null && l2 !=null){
if(l1.val + l2.val + flag >=10){
node = (l2.val + l1.val +flag)%10 ;
flag = 1;
}else{
node = l2.val + l1.val +flag ;
flag = 0 ;
}
ans.next = new ListNode(node);
ans = ans.next;
l2 = l2.next;
l1 = l1.next;
}
while(l1 != null ){
node = l1.val + flag;
ans.next = new ListNode(node %10);
flag = node /10;
ans = ans.next;
l1 = l1.next;
}
while(l2 != null){
node = l2.val + flag;
ans.next = new ListNode(node %10);
flag = node /10;
ans = ans.next;
l2 = l2.next;
}
if(flag != 0 ){
ans.next = new ListNode(flag);
}
return yummy.next;
}
}
|