Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active June 25, 2016 14:20
Show Gist options
  • Save dgodfrey206/95c63bc46a06d17b842afb9aeadd8bad to your computer and use it in GitHub Desktop.
Save dgodfrey206/95c63bc46a06d17b842afb9aeadd8bad to your computer and use it in GitHub Desktop.
struct ListNode {
int val;
struct ListNode* next;
ListNode(int val) : val(val), next(0) {}
};
struct ListNode* newNode(int data) {
return new struct ListNode(data);
}
struct ListNode* Sum(struct ListNode* l1, struct ListNode* l2, int carry) {
// add the numbers with the carry (initially 0)
int sum = carry + l1->val + l2->val;
// the digit to carry over to the next sum
int digitToCarry = sum/10;
// insert the last digit
struct ListNode* result = newNode(sum % 10);
if (!l1->next || !l2->next) {
// check if we are at the end of the list, if so,
// check if there is another digit to insert and insert it
if (!l1->next && !l2->next) {
// a check for sum>=10 is done so that we don't append a trailing 0
if (sum >= 10) result->next = newNode(digitToCarry);
return result;
}
// if the second list is longer, append zeros to the first
if (!l1->next) l1->next = newNode(0);
// if the first list is longer, append zeros to the second
if (!l2->next) l2->next = newNode(0);
}
// compute the rest of the sum and append to result
result->next = Sum(l1->next, l2->next, digitToCarry);
return result;
}
struct ListNode* Sum(struct ListNode* l1, struct ListNode* l2) {
return Sum(l1,l2,0);
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return Sum(l1, l2);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment