-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
50 lines (44 loc) · 1.03 KB
/
Solution.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 <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
using namespace std;
class Solution {
private:
ListNode* addWithCarry(ListNode* l1, ListNode* l2, int carry) {
if (!l1 && !l2 && carry == 0) {
return nullptr; // end of number
}
int l1Val = 0;
int l2Val = 0;
ListNode* l1Next = nullptr;
ListNode* l2Next = nullptr;
if (l1) {
l1Val = l1->val;
l1Next = l1->next;
}
if (l2) {
l2Val = l2->val;
l2Next = l2->next;
}
int sum = l1Val + l2Val + carry;
return new ListNode(sum % 10, addWithCarry(l1Next, l2Next, sum / 10));
}
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return addWithCarry(l1, l2, 0);
}
};