C++ Recursive Solution (45ms)


  • 0
    U
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            return add(l1, l2, 0);
        }
        
        ListNode* add(ListNode* l1, ListNode* l2, bool carry) {
            int sum = carry;
            
            if(l1 == 0 && l2 == 0)
            {
                return carry ? new ListNode(1) : 0;
            }
            
            if(l1 != 0)
            {
                sum += l1->val;
            }
            
            if(l2 != 0)
            {
                sum += l2->val;
            }
            
            ListNode* ret = l1 ? l1 : l2;
            ret->val = sum % 10;
            ret->next = add(l1 ? l1->next : 0, l2 ? l2->next : 0, sum > 9);
            return ret;
        }
    };
    

Log in to reply
 

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