C++ clear 12-line solution


  • 0
    H
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if(!l1 || !l2) return !l1 ? l2 : l1;
            ListNode *prehead = new ListNode(0), *pre = prehead;
            int sum = 0;
            while(l1 || l2) {
                sum /= 10;
                if(l1) {sum += l1->val; l1 = l1->next;}
                if(l2) {sum += l2->val; l2 = l2->next;}
                pre->next = new ListNode(sum % 10);
                pre = pre->next;
            }
            if(sum / 10) pre->next = new ListNode(sum / 10);
            return prehead->next;
        }
    };
    

Log in to reply
 

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