Saturday, October 29, 2016

Leetcode 2: Add Two Numbers Solution

Problem statement could be found @https://leetcode.com/problems/add-two-numbers/

Solution-

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
       
        if (l1 == NULL)                                
            return l2;
        if (l2 == NULL)
            return l1;
       
        ListNode *sNode = new ListNode((l1->val+l2->val)%10);              
        int carry = (l1->val+l2->val)/10;
        ListNode *temp = sNode;
        l1 = l1->next;
        l2= l2->next;
       
        while (l1 != NULL && l2!=NULL){
           int v = l1->val+l2->val + carry;  
           temp->next = new ListNode(v%10) ;
           carry = v/10;
           temp = temp->next;
           l1 = l1->next;
           l2 = l2->next;
        }
        ListNode *p = NULL;
        if (l1 == NULL && l2 !=NULL){
            p = l2;
        }
        if (l2 == NULL && l1 !=NULL){
            p = l1;
        }  
        while (p!=NULL){
           int v = p->val+ carry;  
           temp->next = new ListNode(v%10) ;
           carry = v/10;
           temp = temp->next;
           p = p->next;
         
        }
        if (carry !=0){
            temp->next = new ListNode(carry);
        }
        return sNode;
    }                                                                                                                                                          
   
};

Status - Accepted by Leetcode

No comments:

Post a Comment