Created
July 3, 2024 14:14
-
-
Save AmosAidoo/7a2ec4e5030ae22c2b3cdc6c91b1c300 to your computer and use it in GitHub Desktop.
LeetCode Add Two Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode() : val(0), next(nullptr) {} | |
* ListNode(int x) : val(x), next(nullptr) {} | |
* ListNode(int x, ListNode *next) : val(x), next(next) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | |
ListNode* res = new ListNode; | |
ListNode *res_cpy = res; | |
ListNode *l1_cpy = l1, *l2_cpy = l2; // So that l1 and l2 are not mutated | |
int curry = 0; | |
while (l1_cpy != nullptr || l2_cpy != nullptr) { | |
int sum = 0; | |
if (l1_cpy != nullptr) { | |
sum += l1_cpy->val; | |
l1_cpy = l1_cpy->next; | |
} | |
if (l2_cpy != nullptr) { | |
sum += l2_cpy->val; | |
l2_cpy = l2_cpy->next; | |
} | |
sum += curry; | |
res_cpy->val = sum%10; | |
curry = sum/10; | |
if (l1_cpy == nullptr && l2_cpy == nullptr) { | |
if (curry) res_cpy->next = new ListNode(curry); | |
break; | |
} | |
res_cpy->next = new ListNode; | |
res_cpy = res_cpy->next; | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment