Add Two Numbers
This commit is contained in:
23
src/s2_add_two_numbers.cpp
Normal file
23
src/s2_add_two_numbers.cpp
Normal 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;
|
||||
}
|
Reference in New Issue
Block a user