# Monthly Archives: November 2015

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

```class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ans = new ListNode(0), *tail;
tail = ans;
int sum, carry=0;
while (l1 && l2)
{
sum = l1->val + l2->val + carry;
if (sum >= 10)
{
carry = 1;
sum = sum % 10;
}
else
carry = 0;
ListNode *ln = new ListNode(0);
tail->next = ln;
tail = tail->next;
tail->val = sum;
l1 = l1->next;
l2 = l2->next;
}
while (l1)
{
sum = l1->val + carry;
if (sum >= 10)
{
carry = 1;
sum = sum % 10;
}
else
carry = 0;
ListNode *ln = new ListNode(0);
tail->next = ln;
tail = tail->next;
tail->val = sum;
l1 = l1->next;
}
while (l2)
{
sum = l2->val + carry;
if (sum >= 10)
{
carry = 1;
sum = sum % 10;
}
else
carry = 0;
ListNode *ln = new ListNode(0);
tail->next = ln;
tail = tail->next;
tail->val = sum;
l2 = l2->next;
}
if (carry)
{
ListNode *ln = new ListNode(0);
tail->next = ln;
tail = tail->next;
tail->val = 1;
}
return ans->next;
}
};
```

```class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = NULL, *prev = NULL;
int sum, carry=0;
while (l1 || l2)
{
int v1 = l1 ? l1->val : 0;
int v2 = l2 ? l2->val : 0;
sum = v1 + v2 + carry;
carry = sum >= 10 ? 1 : 0;
sum %= 10;
ListNode *ln = new ListNode(sum);
if (prev)
prev->next = ln;
prev = ln;
l1 = l1 ? l1->next : NULL;
l2 = l2 ? l2->next : NULL;
}
if (carry)
{
ListNode *ln = new ListNode(carry);
prev->next = ln;
}