clear c++ solution with o(1) space.


  • 0
    J
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* sum = new ListNode(0);
            ListNode* helper = sum;
            int carry = 0;
            while(l1 || l2 || carry){
                int tmp = ((l1? l1->val : 0) + (l2 ? l2->val : 0) + carry);
                sum->next = l1 ? l1: (l2 ? l2 : (new ListNode(carry)));    //use l1 or l2 to store the result so we don't need extra space.
                sum->next->val = tmp%10;
                sum = sum->next;
                carry = tmp/10;
                if(l1) l1 = l1->next;
                if(l2) l2 = l2->next;
            }
            return helper->next;
        }
    };
    

Log in to reply
 

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