-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTwoHugeNumbers.cpp
68 lines (60 loc) · 1.41 KB
/
addTwoHugeNumbers.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
/* addTwoHugeNumbers from CodeFights */
// Definition for singly-linked list:
// template<typename T>
// struct ListNode {
// ListNode(const T &v) : value(v), next(nullptr) {}
// T value;
// ListNode *next;
// };
//
ListNode<int>* addTwoHugeNumbers(ListNode<int> * a, ListNode<int> * b) {
std::stack<int> num1;
std::stack<int> num2;
ListNode<int> *p = a;
while (p != nullptr) {
num1.push(p->value);
p = p->next;
}
p = b;
while (p != nullptr) {
num2.push(p->value);
p = p->next;
}
int x = 0;
int carry = 0;
ListNode<int> *head = nullptr;
while (!num1.empty() && !num2.empty()) {
x = num1.top() + num2.top() + carry;
num1.pop();
num2.pop();
carry = x / 10000;
x = x % 10000;
p = new ListNode(x);
p->next = head;
head = p;
}
while (!num1.empty()) {
x = num1.top() + carry;
num1.pop();
carry = x / 10000;
x = x % 10000;
p = new ListNode(x);
p->next = head;
head = p;
}
while(!num2.empty()) {
x = num2.top() + carry;
num2.pop();
carry = x / 10000;
x = x % 10000;
p = new ListNode(x);
p->next = head;
head = p;
}
if (carry > 0) {
p = new ListNode(carry);
p->next = head;
head = p;
}
return head;
}