LeetCode【2】Add two numbers

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

AC代码如下:

ListNode* add(ListNode* l1, ListNode* l2,int len1,int len2){
    if(len1 <len2)
        return add(l2,l1,len2,len1);
    //len1>=len2;
    ListNode* tmp1=l1;
    ListNode* tmp2=l2;
    int jin=0;
    while(tmp2!=NULL)
    {
        int now = (tmp1->val+tmp2->val)+jin;
        if(now>=10)
        {
            jin = now/10;
            now = now-10;
        }
        else
        {
            jin= 0;
        }
        tmp1->val = now;
        tmp1=tmp1->next;
        tmp2=tmp2->next;
    }
    for(;jin>0,tmp1!=NULL;tmp1=tmp1->next)
    {
        int now = jin + tmp1->val;
        if(now >= 10)
        {
            jin = now/10;
            now = now-10; 
        }
        else
        {
            jin=0;
        }
        tmp1->val = now;

    }
    if(tmp1==NULL&&jin>0)
    {   
        //ListNode node(jin);
        ListNode* nodenew = new ListNode(jin);
        ListNode *tmp=l1;
        for(;tmp->next!=NULL;tmp=tmp->next)
            ;
        tmp->next = nodenew;
    }
    return l1;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    if(l1 == NULL && l2 == NULL)
        return NULL;
    else if(l1 == NULL)
        return l2;
    else if(l2 == NULL)
        return l1;
    else
    {
        int len1=0,len2=0;
        ListNode* tmp;
        for(tmp=l1;tmp!=NULL;tmp=tmp->next)
        {
            len1++;
        }
        for(tmp=l2;tmp!=NULL;tmp=tmp->next)
        {
            len2++;
        }
        return add(l1,l2,len1,len2);
    }
}

别人写的,也差不多。主要需要考虑进位的事情。有多种情况。两个链表长度相等时,只要最后有进位,就直接放到后面。如果不等,则把长度小的数加到长度较大的数上,然后判断进位。

原文地址:https://www.cnblogs.com/ww-jin/p/4445614.html