Description of the Problem
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Thinking Process
From given input above, we should calculate result = 807 = 342 + 465, and construct a linked list by inserting the result's digits in reverse order.
In order to solve this problem, we first need to retrieve the entries in the two given linked lists and reverse the order to get two numbers to add. Then we add these two numbers up, getting the result, and construct a linked list from it.
When it comes to reversing, stack is the first thing that comes to my mind, for its characteristic of FILO.
Inefficient Solution
class Solution {
public:
string BigIntAdding(string int1, string int2) {
string adder = int1.length() >= int2.length() ? int1 : int2;
string addee = int1.length() < int2.length() ? int1 : int2;
int diff = adder.length() - addee.length();
while (diff--)
addee.insert(addee.begin(), '0');
string overflow;
overflow.resize(adder.length());
string result;
result.resize(adder.length());
for (auto i : overflow)
i = '0';
for (int i = adder.size() - 1; i >= 1; i--) {
int tempadder = atoi(adder.substr(i, 1).c_str());
int tempaddee = atoi(addee.substr(i, 1).c_str());
int tempresult = tempadder + tempaddee + atoi(overflow.substr(i,1).c_str());
overflow[i - 1] = 48 + tempresult / 10;
result[i] = 48 +tempresult%10;
}
int tempadder = atoi(adder.substr(0, 1).c_str());
int tempaddee = atoi(addee.substr(0, 1).c_str());
int tempresult = tempadder + tempaddee + atoi(overflow.substr(0, 1).c_str());
result[0] = tempresult%10 + '0';
if (tempresult >= 10)
result.insert(result.begin(), 1 + '0');
return result;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> sta1;
stack<int> sta2;
while (l1 != NULL) {
sta1.push(l1->val);
l1 = l1->next;
}
while (l2 != NULL) {
sta2.push(l2->val);
l2 = l2->next;
}
string int1, int2;
while (!sta1.empty()) {
int temp1;
temp1 = sta1.top();
sta1.pop();
int1 += to_string(temp1);
}
while (!sta2.empty()) {
int temp2;
temp2 = sta2.top();
sta2.pop();
int2 += to_string(temp2);
}
long long int i1 = atoi(int1.c_str());
long long int i2 = atoi(int2.c_str());
long long int result = i1 + i2;
string tempt = to_string(result);
string res;
if (tempt.length() >= 8)
res = BigIntAdding(int1, int2);
else
res = tempt;
string reverse;
for (int i = 0; i < res.size(); i++) {
reverse += res[res.size() - 1 - i];
}
int count = 0;
ListNode* Head = new ListNode(atoi(reverse.substr(count++, 1).c_str()));
ListNode* temp = Head;
while (count < reverse.size()) {
Head->next = new ListNode(atoi(reverse.substr(count++, 1).c_str()));
Head = Head->next;
}
return temp;
}
};