-
Notifications
You must be signed in to change notification settings - Fork 7
/
add_two_numbers.cpp
92 lines (80 loc) · 2.16 KB
/
add_two_numbers.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 44 ms solution, O(max(m,n)) => space and time complexity both
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l3_head = new ListNode(0);
auto l3 = l3_head;
int carry = 0;
while (l1 != NULL and l2 != NULL){
l3->next = new ListNode( l1->val + l2->val + carry );
carry = l3->next->val / 10;
l3->next->val -= carry * 10;
l3 = l3->next;
l1 = l1->next;
l2 = l2->next;
}
ListNode* temp;
if (l1 == NULL)
temp = l2;
else
temp = l1;
while (temp != NULL){
l3->next = new ListNode( temp->val + carry );
carry = l3->next->val / 10;
l3->next->val -= carry * 10;
temp = temp->next;
l3 = l3->next;
}
if (carry > 0){
l3->next = new ListNode( carry );
}
l3_head = l3_head->next;
return l3_head;
}
};
// 16 ms solution - Credit: LeetCode
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
auto desyncio = []()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* root = NULL, *current = NULL;
int c = 0;
while(l1 || l2 || c) {
int x = l1 ? l1->val : 0;
int y = l2 ? l2->val : 0;
int z = x + y + c;
int r = z % 10;
c = z/10;
if(!current) {
root = current = new ListNode(r);
} else {
current->next = new ListNode(r);
current = current->next;
}
l1 = l1 ? l1->next: NULL;
l2 = l2 ? l2->next: NULL;
}
return root;
}
};