-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path2-add-two-numbers.cpp
50 lines (46 loc) · 1.4 KB
/
2-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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode head(0);
ListNode* dummy = &head;
int carry = 0;
while (l1 && l2) {
int next_val = (l1->val + l2->val + carry) % 10;
carry = (l1->val + l2->val + carry) / 10;
dummy->next = new ListNode(next_val);
l1 = l1->next;
l2 = l2->next;
dummy = dummy->next;
}
if (l1 && !l2) {
while (l1) {
int next_val = (l1->val + carry) % 10;
carry = (l1->val + carry) / 10;
dummy->next = new ListNode(next_val);
l1 = l1->next;
dummy = dummy->next;
}
} else if (!l1 && l2) {
while (l2) {
int next_val = (l2->val + carry) % 10;
carry = (l2->val + carry) / 10;
dummy->next = new ListNode(next_val);
l2 = l2->next;
dummy = dummy->next;
}
}
if (carry) {
dummy->next = new ListNode(carry);
dummy = dummy->next;
}
return head.next;
}
};