|
| 1 | +/* |
| 2 | +Add Two Numbers |
| 3 | +=============== |
| 4 | +
|
| 5 | +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 contains a single digit. Add the two numbers and return the sum as a linked list. |
| 6 | +
|
| 7 | +You may assume the two numbers do not contain any leading zero, except the number 0 itself. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: l1 = [2,4,3], l2 = [5,6,4] |
| 11 | +Output: [7,0,8] |
| 12 | +Explanation: 342 + 465 = 807. |
| 13 | +
|
| 14 | +Example 2: |
| 15 | +Input: l1 = [0], l2 = [0] |
| 16 | +Output: [0] |
| 17 | +
|
| 18 | +Example 3: |
| 19 | +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
| 20 | +Output: [8,9,9,9,0,0,0,1] |
| 21 | +
|
| 22 | +Constraints: |
| 23 | +The number of nodes in each linked list is in the range [1, 100]. |
| 24 | +0 <= Node.val <= 9 |
| 25 | +It is guaranteed that the list represents a number that does not have leading zeros. |
| 26 | +*/ |
| 27 | + |
| 28 | +/** |
| 29 | + * Definition for singly-linked list. |
| 30 | + * struct ListNode { |
| 31 | + * int val; |
| 32 | + * ListNode *next; |
| 33 | + * ListNode() : val(0), next(nullptr) {} |
| 34 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 35 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 36 | + * }; |
| 37 | + */ |
| 38 | + |
| 39 | +class Solution |
| 40 | +{ |
| 41 | +public: |
| 42 | + ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) |
| 43 | + { |
| 44 | + ListNode *dummy = new ListNode(-1); |
| 45 | + auto temp = dummy; |
| 46 | + int carry = 0; |
| 47 | + |
| 48 | + while (l1 || l2 || carry) |
| 49 | + { |
| 50 | + int n1 = l1 ? l1->val : 0; |
| 51 | + int n2 = l2 ? l2->val : 0; |
| 52 | + |
| 53 | + int sum = n1 + n2 + carry; |
| 54 | + carry = sum / 10; |
| 55 | + sum = sum % 10; |
| 56 | + |
| 57 | + ListNode *newNode = new ListNode(sum); |
| 58 | + temp->next = newNode; |
| 59 | + temp = temp->next; |
| 60 | + |
| 61 | + if (l1) |
| 62 | + l1 = l1->next; |
| 63 | + if (l2) |
| 64 | + l2 = l2->next; |
| 65 | + } |
| 66 | + |
| 67 | + return dummy->next; |
| 68 | + } |
| 69 | +}; |
0 commit comments