Share my recursive solution in cpp


  • 0
    U

    Just recursive way :)

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            return add(l1, l2, 0);
        }
        
        ListNode* add(ListNode* l1, ListNode* l2, int carryBit) {
            if(!l1 && !l2)
                return carryBit ? new ListNode(carryBit) : nullptr;
                
            int v1 = 0, v2 = 0;
            if(l1) v1 = l1->val;
            if(l2) v2 = l2->val;
            int sum = v1 + v2 + carryBit;
            if(sum >= 10) {
                carryBit = 1;
                sum -= 10;
            }
            else
                carryBit = 0;
                
            ListNode* node = new ListNode(sum);
            node->next = add(l1 ? l1->next : nullptr, l2 ? l2->next : nullptr, carryBit);
            return node;
        }
    };

Log in to reply
 

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