Added accepted solutions for leetcode number 1 and 2 problems
This commit is contained in:
43
2-add-two-numbers.cpp
Normal file
43
2-add-two-numbers.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
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 AddTwoNumbersSolution {
|
||||
public:
|
||||
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
|
||||
|
||||
if (!l1 && !l2) return nullptr;
|
||||
|
||||
ListNode* res = new ListNode(0);
|
||||
ListNode* start = res;
|
||||
ListNode* prev(nullptr);
|
||||
|
||||
int carry = 0;
|
||||
while (l1 || l2) {
|
||||
res->val += (l1? l1->val : 0);
|
||||
res->val += (l2? l2->val : 0);
|
||||
res->val += carry;
|
||||
carry = res->val / 10;
|
||||
if (carry) res->val -= 10;
|
||||
|
||||
res->next = new ListNode(0);
|
||||
prev = res;
|
||||
res = res->next;
|
||||
if (l1) l1 = l1->next;
|
||||
if (l2) l2 = l2->next;
|
||||
}
|
||||
if ((carry == 0) && prev) {
|
||||
delete prev->next;
|
||||
prev->next = nullptr;
|
||||
}
|
||||
if (carry > 0) {
|
||||
res->val++;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user