-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2. Add Two Numbers link
111 lines (101 loc) · 2.61 KB
/
2. Add Two Numbers link
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//https://leetcode.com/problems/add-two-numbers/
/**
* 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){
int carry = 0, val;
ListNode* res = new ListNode(0);
ListNode* l = res;
val = l1->val + l2->val;
res->val = val % 10;
carry = val / 10;
l1 = l1->next; l2 = l2->next;
l = res;
while (l1 != NULL || l2 != NULL){
int val1 = l1 == NULL ? 0 : l1->val;
int val2 = l2 == NULL ? 0 : l2->val;
val = val1 + val2 + carry;
ListNode* node = new ListNode(val % 10);
carry = val / 10;
l->next = node;
l = l->next;
if (l1 != NULL)
l1 = l1->next;
if (l2 != NULL)
l2 = l2->next;
}
if (carry != 0){
ListNode* node = new ListNode(carry);
l->next = node;
}
return res;
}
};
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
char delim = ',';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
ListNode* stringToListNode(string input) {
// Generate list from the input
vector<int> list = stringToIntegerVector(input);
// Now convert that list into linked list
ListNode* dummyRoot = new ListNode(0);
ListNode* ptr = dummyRoot;
for(int item : list) {
ptr->next = new ListNode(item);
ptr = ptr->next;
}
ptr = dummyRoot->next;
delete dummyRoot;
return ptr;
}
string listNodeToString(ListNode* node) {
if (node == nullptr) {
return "[]";
}
string result;
while (node) {
result += to_string(node->val) + ", ";
node = node->next;
}
return "[" + result.substr(0, result.length() - 2) + "]";
}
int main() {
string line;
while (getline(cin, line)) {
ListNode* l1 = stringToListNode(line);
getline(cin, line);
ListNode* l2 = stringToListNode(line);
ListNode* ret = Solution().addTwoNumbers(l1, l2);
string out = listNodeToString(ret);
cout << out << endl;
}
return 0;
}