Skip to content

Instantly share code, notes, and snippets.

@DragonOsman
Last active February 6, 2022 15:51
Show Gist options
  • Save DragonOsman/ca318008604cd84736a9734d0d92ec82 to your computer and use it in GitHub Desktop.
Save DragonOsman/ca318008604cd84736a9734d0d92ec82 to your computer and use it in GitHub Desktop.
#include <vector>
#include <algorithm>
#include <sstream>
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l1)
{
return l2;
}
else if (!l2)
{
return l1;
}
ListNode* trav1{l1};
ListNode* trav2{l2};
vector<int> l1_vec;
vector<int> l2_vec;
std::size_t l1_size{};
std::size_t l2_size{};
while (trav1)
{
l1_vec.push_back(trav1->val);
trav1 = trav1->next;
++l1_size;
}
while (trav2)
{
l2_vec.push_back(trav2->val);
trav2 = trav2->next;
++l2_size;
}
if (l1_size == 1 && l2_size == 1)
{
int sum{l1_vec[0] + l2_vec[0]};
ListNode* node{new ListNode(sum, nullptr)};
return node;
}
vector<string> str_nums1;
for (std::size_t i{}; i < l1_vec.size(); ++i)
{
str_nums1.push_back(std::to_string(l1_vec[i]));
}
ostringstream v_str;
std::copy(str_nums1.begin(), str_nums1.end(), ostream_iterator<string>(v_str));
string str_num1{v_str.str()};
vector<string> str_nums2;
for (std::size_t i{}; i < l2_vec.size(); ++i)
{
str_nums2.push_back(std::to_string(l2_vec[i]));
}
ostringstream v_str2;
std::copy(str_nums2.begin(), str_nums2.end(), ostream_iterator<string>(v_str2));
string str_num2{v_str2.str()};
int sum{std::stoi(str_num1) + std::stoi(str_num2)};
vector<ListNode*> sum_vec;
while (sum >= 10)
{
ListNode* node{new ListNode(sum % 10, nullptr)};
sum_vec.push_back(node);
sum /= 10;
}
ListNode* node{new ListNode(sum, nullptr)};
sum_vec.push_back(node); // last digit
for (std::size_t i{}; i < sum_vec.size(); ++i)
{
sum_vec[i]->next = sum_vec[i + 1];
}
sum_vec[sum_vec.size() - 1]->next = nullptr;
return sum_vec[0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment