-
Notifications
You must be signed in to change notification settings - Fork 0
/
#2 AddTwoNumbers.cpp
59 lines (53 loc) · 1.49 KB
/
#2 AddTwoNumbers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Add Two Numbers
//https://leetcode.com/problems/add-two-numbers/
#include <iostream>
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) {
return addTwo(l1, l2, 0);
}
ListNode* addTwo(ListNode* l1, ListNode* l2, bool in_memory) {
if (l1 && l2) {
int ans_dig = in_memory + l1->val + l2->val;
in_memory = ans_dig / 10;
ans_dig = ans_dig % 10;
ListNode* next = addTwo(l1->next, l2->next, in_memory);
return new ListNode(ans_dig, next);
}
else if (l1) {
return addSingle(l1, in_memory);
}
else if (l2) {
return addSingle(l2, in_memory);
}
else if (in_memory) {
return new ListNode(1);
}
else {
return nullptr;
}
}
ListNode* addSingle(ListNode* l, bool in_memory) {
if (l) {
int ans_dig = in_memory + l->val;
in_memory = ans_dig / 10;
ans_dig = ans_dig % 10;
ListNode* next = addSingle(l->next, in_memory);
return new ListNode(ans_dig, next);
}
else if (in_memory) {
return new ListNode(1);
}
else {
return nullptr;
}
}
};