# Monthly Archives: November 2015

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


class Solution {
public:
{
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 *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;
}
};