Leetcode 2. Add Numbers (Java)

Source: Internet
Author: User

Solution:

classSolution { PublicListNode addtwonumbers (listnode L1, ListNode L2) {ListNode L3=NULL; BooleanAdd =false;  while(L1! =NULL|| L2! =NULL) {            //number of bits added            intPlus; if(L1 = =NULL) {plus=L2.val; } Else if(L2 = =NULL) {plus=L1.val; } Else{plus= L1.val +L2.val; }            if(add) {plus++; Add=false; }            //Build NodeListNode temp; if(Plus >= 10) {Temp=NewListNode (plus% 10); Add=true; } Else{Temp=NewListNode (plus); }            //splicing NodesListNode L3head =L3; if(L3 = =NULL) {L3=temp; if(add && (L1 = =NULL|| L1.next = =NULL) && (L2 = =NULL|| L2.next = =NULL) ) {L3.next=NewListNode (1); }            } Else {                 while(L3head.next! =NULL) {L3head=L3head.next; } L3head.next=temp; if(add && (L1 = =NULL|| L1.next = =NULL) && (L2 = =NULL|| L2.next = =NULL) ) {L3Head.next.next=NewListNode (1); }            }            //jump to the next one            if(L1 = =NULL) {L2=L2.next; } Else if(L2 = =NULL) {L1=L1.next; } Else{L1=L1.next; L2=L2.next; }        }        returnL3; }}

At the beginning there are three ways of thinking:

    1. When the converted value is added, it is converted into a linked list, but the values are too large and a long is not sufficient to store
    2. Flips the list to add, but it is easier to add the rounding before it is flipped
    3. Adding and rounding directly using linked lists

Finally, the last thought was adopted.

GitHub Address: Https://github.com/CyanChan/Leetcode-Record

Leetcode 2. 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.