forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0445.cpp
More file actions
40 lines (39 loc) · 962 Bytes
/
0445.cpp
File metadata and controls
40 lines (39 loc) · 962 Bytes
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
class Solution {
public:
ListNode *addRec(ListNode *l1, ListNode *l2, int &carry) {
if (!l1 and !l2)
return nullptr;
ListNode *curr{new ListNode(-1)};
curr->next = addRec(l1->next, l2->next, carry);
curr->val = (l1->val + l2->val + carry) % 10;
carry = (l1->val + l2->val + carry) / 10;
return curr;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *a{l1}, *b{l2};
while (a or b) {
if (!a) {
ListNode *zero{new ListNode(0)};
zero->next = l1;
l1 = zero;
b = b->next;
} else if (!b) {
ListNode *zero{new ListNode(0)};
zero->next = l2;
l2 = zero;
a = a->next;
} else {
a = a->next;
b = b->next;
}
}
int carry{0};
ListNode *head{addRec(l1, l2, carry)};
if (carry) {
ListNode *start{new ListNode(carry)};
start->next = head;
head = start;
}
return head;
}
};