Add Two Numbers
Description
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example Given 7->1->6 + 5->9->2. That is, 617 + 295. Return 2->1->9. That is 912. Given 3->1->5 and 5->9->2, return 8->0->8.
Link
Method
- x
- x
Example
- 1
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ ListNode *addLists(ListNode *l1, ListNode *l2) { // ------------------------------------------------ // Simplified version if (!l1) { return l2; } else if (!l2){ return l1; } ListNode dummy(0); ListNode* prev = &dummy; int sum = 0; int carry = 0; while (l1 || l2) { // get sum // l1 && l2 are not empty if (l1 && l2) { sum = l1->val + l2->val + carry; l1 = l1->next; l2 = l2->next; } else if (l1) { // only l1 is not empty sum = l1->val + carry; l1 = l1->next; } else { // only l2 is not empoty sum = l2->val + carry; l2 = l2->next; } // update result carry = sum / 10; sum %= 10; prev->next = new ListNode(sum); prev = prev->next; } if (carry > 0) { prev->next = new ListNode(carry); } return dummy.next; // ---------------------------------------------------- // naive version if (!l1) { return l2; } else if (!l2){ return l1; } ListNode dummy(0); ListNode* prev = &dummy; int sum = 0; int carry = 0; while (l1 || l2) { if (l1 && l2) { sum = l1->val + l2->val + carry; carry = sum / 10; sum %= 10; prev->next = new ListNode(sum); l1 = l1->next; l2 = l2->next; prev = prev->next; } else if (l1) { sum = l1->val + carry; carry = sum / 10; sum %= 10; prev->next = new ListNode(sum); l1 = l1->next; prev = prev->next; } else if (l2) { sum = l2->val + carry; carry = sum / 10; sum %= 10; prev->next = new ListNode(sum); l2 = l2->next; prev = prev->next; } } if (carry > 0) { prev->next = new ListNode(carry); } return dummy.next; } };
Similar problems
x
Tags
x