Simple C++ 46ms


  • 0
    T
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* sent = new ListNode(777);
            ListNode* ptr = sent;
            int carry = 0;
            while (l1 || l2) {
                carry /= 10;
                ptr->next = new ListNode(carry);
                
                if (l1) { carry += l1->val; l1 = l1->next; }
                if (l2) { carry += l2->val; l2 = l2->next; }
                
                ptr->next->val = carry % 10;
                
                ptr = ptr->next;
            }
            if (carry >= 10) ptr->next = new ListNode(carry/10);
            return sent->next;
        }
    };
    

Log in to reply
 

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