Monday, November 25, 2013

LeetCode Problem : Add Two Numbers

Problem

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Code

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int carry = 0;
    ListNode *head = 0,*node = 0;
    while(l1 || l2){
        int num1 = 0,num2 = 0;
        if(l1){
            num1 = l1->val;
            l1 = l1->next;
        }
        if(l2){
            num2 = l2->val;
            l2 = l2->next;
        }
        int sum = num1 + num2 + carry;
        carry = sum / 10;
        sum = sum % 10;
        if(!head){
            head = new ListNode(sum);
            node = head;
        }
        else{
            node->next = new ListNode(sum);
            node = node->next;
        }
    }
    if(carry > 0)
        node->next = new ListNode(carry);
    return head;
}

No comments:

Post a Comment