C++ solution / 58 ms


  • 0
    P
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            ListNode* sum = new ListNode(INT_MAX);
            ListNode* head = sum;
            int carry = 0;
            while(l1 && l2) {
                int s = l1->val + l2->val + carry;
                sum->next = new ListNode(s%10);
                carry = s/10;
                l1 = l1->next;
                l2 = l2->next;
                sum = sum->next;
            }
            addList(l1, sum, carry);
            addList(l2, sum, carry);
            return head->next;
        }
        
        inline void addList(ListNode* l, ListNode*& head, int& carry) {
          while(l) {
                int num = l->val + carry ;
                head->next = new ListNode(num%10);
                carry = num/10;
                head = head->next;
                l = l->next;
          } 
          if (carry) {
              head->next = new ListNode(carry);
          }
        }
    };

  • 0
    S

    class Solution {
    public:
    ListNode *addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode
    head = NULL;
    ListNode
    node = NULL;

        int v1 = 0;
        int v2 = 0;
        int sum = 0;
        int mod = 0;
        int ext = 0;
    
        while ( NULL != l1 || NULL != l2 || ext > 0) {
            v1 = l1 ? l1->val : 0;
            v2 = l2 ? l2->val : 0;
            
            sum = v1 + v2 + ext;
            mod = sum % 10;
            ext = (sum - mod) / 10;
    
            if (head) {
              node->next = new ListNode( mod );
              node = node->next;
            } else {
              head = new ListNode( mod );
              node = head;
            }
            
            l1 = l1 ? l1->next : NULL;
            l2 = l2 ? l2->next : NULL;
        }
        
        return head; 
    }
    

    };


Log in to reply
 

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