Add Two Numbers

This commit is contained in:
2022-03-10 20:25:55 +08:00
parent 63885a6fac
commit c8b542689c
3 changed files with 107 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
#include "s2_add_two_numbers.hpp"
ListNode* Solution::addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *l_begin = new ListNode((l1->val + l2->val) % 10);
ListNode *l_end = l_begin;
int carry{ (l1->val + l2->val) >= 10 ? 1 : 0 };
while (l1->next != nullptr || l2->next != nullptr || carry != 0) {
if (l1->next == nullptr && l2->next != nullptr) {
l1->next = new ListNode(0);
} else if (l1->next != nullptr && l2->next == nullptr) {
l2->next = new ListNode(0);
} else if (l1->next == nullptr && l2->next == nullptr && carry != 0) {
l1->next = new ListNode(0);
l2->next = new ListNode(0);
}
l1 = l1->next;
l2 = l2->next;
l_end->next = new ListNode((l1->val + l2->val + carry) % 10);
l_end = l_end->next;
carry = (l1->val + l2->val + carry) >= 10 ? 1 : 0;
}
return l_begin;
}