forked from fuellee/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbers.cpp
50 lines (45 loc) · 1.25 KB
/
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
#include <iostream>
#include "ListNode.hpp"
// Definition for singly-linked list.
using namespace std;
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2, int c=0) {
if(l1==nullptr && l2==nullptr)
return (c==1)? new ListNode(1): nullptr;
else if(l1==nullptr || l2==nullptr){
ListNode *l=(l2==nullptr)? l1:l2;
int val = l->val + c;
c = val/10;
val = val%10;
ListNode *result = new ListNode(val);
result->next = addTwoNumbers(nullptr, l->next, c);
return result;
}
else {
int val = l1->val + l2->val + c;
c = val/10;
val = val%10;
ListNode *result = new ListNode(val);
result->next = addTwoNumbers(l1->next, l2->next, c);
return result;
}
}
};
int main() {
#define N new ListNode
Solution s;
ListNode *l1 = N(2,N(4,N(3)));
ListNode *l2 = N(5,N(6,N(4)));
s.addTwoNumbers(l1,l2)->show();
l1 = N(5);
l2 = N(5);
s.addTwoNumbers(l1,l2)->show();
l1 = N(9,N(8));
l2 = N(1);
s.addTwoNumbers(l1,l2)->show();
l1 = N(1,N(8));
l2 = N(0);
s.addTwoNumbers(l1,l2)->show();
return 0;
}