You are given, non-empty linked lists representing and non-negative integers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
You may assume the numbers does not contain any leading zero, except the number 0 itself.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
Positioning: Medium problem
Test instructions Simple, two inverted nonnegative integers, stored with a linked list, and the definition of a list class also gives:
public class ListNode {
int Val;
ListNode Next;
ListNode (int x) {val = x;}
}
Now to add the two number of the resulting number is also inverted with the linked list storage, because the reason has been inverted, low in front, direct processing, continue to advance to high.
Need to pay attention to is the rounding problem, when all is done, and finally there is a carry existence, the end of the list to add a node, the value is 1, that is, the highest bit is 1.
Java implementations:
1 Public classSolution {2 PublicListNode addtwonumbers (listnode L1, ListNode L2) {3ListNode listnode=NewListNode (0);4 ListNode ptr1,ptr2,ptr;5 intAddp=0;6 intNow ;7ptr1=L1;8Ptr2=L2;9Ptr=ListNode;Ten while(ptr1!=NULL&&ptr2!=NULL){ Onenow=ptr1.val+ptr2.val+ADDP; AAddp=0; - if(now>9){ -addp++; thenow-=10; - } -ptr.next=NewListNode (now); -Ptr=Ptr.next; +ptr1=Ptr1.next; -Ptr2=Ptr2.next; + } A while(ptr1!=NULL){ atnow=ptr1.val+ADDP; -Addp=0; - if(now>9){ -addp++; -now-=10; - } inptr.next=NewListNode (now); -Ptr=Ptr.next; toptr1=Ptr1.next; + } - while(ptr2!=NULL){ thenow=ptr2.val+ADDP; *Addp=0; $ if(now>9){Panax Notoginsengaddp++; -now-=10; the } +ptr.next=NewListNode (now); APtr=Ptr.next; thePtr2=Ptr2.next; + } - if(addp==1){ $ptr.next=NewListNode (ADDP); $ } - returnListnode.next; - } the}
Leetcode 002 Add-Numbers-java