C++ 36ms solution


  • 2
    B
    class Solution 
    {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
        ListNode* retPre=new ListNode(0);
        ListNode* mov=retPre;
        int sum=0;
        int added=0;
        while((l1!=NULL) || (l2!=NULL))
        {
            sum=0;
            if(l1!=NULL)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            else
            {
                sum+=0;
            }
            
            if(l2!=NULL)
            {
                sum+=l2->val;
                l2=l2->next;
            }
            else
            {
                sum+=0;
            }
            
            sum+=added;
            added=sum/10;
            sum=sum%10;
            mov->next=new ListNode(sum);
            mov=mov->next;
            
        }
        if(added!=0){mov->next=new ListNode(added);}
        ListNode* ret=retPre->next;
        delete retPre;
        return ret;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.