Fastest C++ solution - 26ms


  • 0
    S

    /**

    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      class Solution {
      public:
      ListNode
      addTwoNumbers(ListNode* l1, ListNode* l2) {

       ListNode* sum_list = new ListNode(0);
       //ListNode* sum_list;
       auto p = sum_list; // head 
       int carry =0;
       int first_digit = 0;
       auto l1_d = l1;
       auto l2_d = l2;
       
       while (l1_d && l2_d){
           //cout << "in here\n";
           int sum = l1_d->val + l2_d->val+carry; // get sum
           first_digit = getFirstDigit(sum);
           insert(p,first_digit);
           carry = getSecondDigit(sum);
           l1_d = l1_d->next;
           l2_d = l2_d->next;
           
       }
       
       while (l1_d){
           int sum = l1_d->val + carry;
           first_digit = getFirstDigit(sum);
           carry = getSecondDigit(sum);
           insert(p,first_digit);
           l1_d = l1_d->next;
       }
       
       while(l2_d){
           int sum = l2_d->val + carry;
           first_digit = getFirstDigit(sum);
           carry = getSecondDigit(sum);
           insert(p,first_digit);
           l2_d = l2_d->next;
       }
       
       if (carry!=0)
           insert(p,carry);
       //cout << "returning here \n";
       p = sum_list;
       sum_list = sum_list->next;
       delete p;
       return sum_list;
      

      }

      void insert(ListNode*& node,int digit){
      node->next = new ListNode(digit);
      //node = new ListNode(digit+carry);
      node = node->next; // go to next node
      }

      int getFirstDigit(int sum){
      return sum%10;
      }

      int getSecondDigit(int sum){
      return sum/10;
      }
      };


Log in to reply
 

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