Leetcode 002 Add-Numbers-java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.