-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0002-add-two-numbers.cpp
63 lines (51 loc) · 1.42 KB
/
0002-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
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = nullptr;
ListNode *c1 = l1, *c2 = l2, *cur = nullptr;
int8_t carry = 0;
while (c1 && c2) {
int8_t sum = c1->val + c2->val + carry;
carry = sum / 10;
ListNode* node = new ListNode(sum % 10);
if (!head) {
head = node;
} else {
cur->next = node;
cur = node;
}
cur = node;
c1 = c1->next;
c2 = c2->next;
}
while (c1) {
int8_t sum = c1->val + carry;
carry = sum / 10;
ListNode* node = new ListNode(sum % 10);
if (!head) {
head = node;
} else {
cur->next = node;
cur = node;
}
cur = node;
c1 = c1->next;
}
while (c2) {
int8_t sum = c2->val + carry;
carry = sum / 10;
ListNode* node = new ListNode(sum % 10);
if (!head) {
head = node;
} else {
cur->next = node;
cur = node;
}
cur = node;
c2 = c2->next;
}
if (carry)
cur->next = new ListNode(carry);
return head;
}
};