You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Output: 7 -> 0 -> 8
code:
public class add2Numbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode iter1 = l1, iter2 = l2, newList = new ListNode(0), tail = newList;
int carry = 0, sum;
while(iter1 != null || iter2 != null){
sum = carry;
if(iter1 != null){
sum += iter1.val;
iter1 = iter1. next;
}
if(iter2 != null){
sum += iter2.val;
iter2 = iter2.next;
}
carry = sum / 10;
sum %= 10;
tail.next = new ListNode(sum);
tail = tail.next;
}
if(carry != 0){
tail.next = new ListNode(carry);
}
return newList.next;
}
}
No comments:
Post a Comment