Skip to content

Instantly share code, notes, and snippets.

@gladilindv
Last active March 22, 2018 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladilindv/a69fbc4b61c952a7d975a82466f840bf to your computer and use it in GitHub Desktop.
Save gladilindv/a69fbc4b61c952a7d975a82466f840bf to your computer and use it in GitHub Desktop.
std::string sum(const std::string& a, const std::string& b)
{
std::string res(std::max(a.size(), b.size()) + 1, '0');
auto iterA = a.rbegin();
auto iterB = b.rbegin();
auto iter = res.rbegin();
static const auto addIter = [&iter](decltype(iterA)& iterA, const std::string& a)
{
if(iterA != a.rend())
{
*iter += *iterA - '0';
if(*iter > '9')
{
auto tmpIter = iter;
++tmpIter;
*tmpIter = '1';
*iter -= 10;
}
++iterA;
}
};
while(iter != res.rend())
{
addIter(iterA, a);
addIter(iterB, b);
++iter;
}
if(res[0] == '0')
{
res.erase(0, 1);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment